I came across this code somewhere when practicing basic C questions:
int func(num) {
if (num > 0) {
return (num + func(num - 2));
}
}
int main() {
printf("%d\n", func(5));
return 0;
}
The code when executed returns 8 as the answer. But I think that the answer should be "cannot be determined".
The recursive calls in my head looks like this:
5 + func(3) => 5 + (3 + func(1))
3 + func(1) => 3 + (1 + func(-1))
1 + func(-1) => 1 + (?)
For the ? symbol, I think reading the return value for func(-1) is undefined behavior. I'm basing this on the assumption that for func(-1) no explicit int value is being returned. So reading from func(-1) in the expression (1 + func(-1)) should produce some garbage result + 1 in my opinion.
Why is that the code is returning 8 as the answer and not something garbage?
When I explicitly pass a negative number to func and read the result I do get the garbage value, such as in this code;
int main() {
printf("%d\n", (1 + func(-1))); // returns garbage result and not 0
return 0;
}
Why is that in the recursive call (1 + func(-1)) is being evaluated to 0 value?
I compiled the code on a 64-bit machine with gcc as gcc myfile.c. Compiling the code as gcc -W -Wall -ansi -pedantic myfile.c gives warning about the func function, but that's not the point. I am unable to figure out how 8 is the answer.