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

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -