23 views
Consider the following code:

int bar(int val)

{

int x=0;

while(val>0){

x=x+bar(val-1);

}

return val;

}
Where does the difference in the functioning of the code occur when the statement x=x+bar(val-1);  in the above code gets replaced by x=x+bar(--val);

Please explain the difference between both of them and the way the logic works.
| 23 views

When you use

x = x + bar(val - 1);

here the value used for calling bar function is (val - 1), but the variable 'val' itself isn't decremented. Therefore val doesn't change at all, and the program is unable to break out of the while loop. So the program falls into an infinite loop (but the computer has finite memory and each function call consumes some stack space, therefore the program terminates when the computer runs out of memory).

When you use

x = x + bar(--val);

In this case, 'val' is decremented. Therefore the while loop breaks out at some point and the program is able to terminate properly.

by (17 points)