c - Why is this function giving me infinite loop? -
int bar(int val) { int x = 0; while(val > 0) { x= x + bar(val-1); } return val; } i calling function bar(3). going in infinite loop. why?
here's visualization of what's happening may explain (the expressions val , val - 1 replaced actual values each iteration):
bar(3): while ( 3 > 0 ) { x = x + bar(2); } bar(2): while ( 2 > 0 ) { x = x + bar(1); } bar(1): while ( 1 > 0 ) { x = x + bar(0); } bar(0): return 0; bar(1); while ( 1 > 0 ) { x = x + bar(0); } bar(0): return 0; bar(1): while ( 1 > 0 ) { x = x + bar(0); } bar(0); return 0; hopefully issue clear - when bar(0) returns, val 1 again, loop in bar(1) executes again.
you probably want replace while if - way, sequence of execution is
bar(3): if ( 3 > 0 ) { x = x + bar(2); } bar(2): if ( 2 > 0 ) { x = x + bar(1); } bar(1): if ( 1 > 0 ) { x = x + bar(0); } bar(0): return 0; bar(1): return 1; bar(2): return 2; bar(3): return 3;
Comments
Post a Comment