so I was playing around with recursion in C and I am not sure why is this happening:
code A
int foo(int x)
{
if (x==0) return 0;
else return foo(--x)+x;
}
int main() { printf("%d\n", foo(10));
code B
int foo(int x)
{
if (x==0) return 0;
else return foo(x--)+x;
}
int main() { printf("%d\n", foo(10));
Code A prints 45 instead of 55 and I figured that out. It is because the recursive call gets unwounded this way: 9+8+7+...+0 = 45
Code B on the other hand gets stuck and never returns to the prompt!! i have to ctrl+c it. Why does it get stuck? Is it because it never decrements past 10?
That's because in snippet B x gets decremented after the recursive call so the function is always called with foo(10)
EDIT:
As James McNellis pointed out in its comment x gets decremented before calling the function but its original value is used in the call instead of the decremented one.
Basically the expression x-- is evaluated before foo(x--) but its value is actually x, therefore the function is called with x = 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With