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.
Why garbage value is not being returned in a recursive call to a function with undefined behavior?
Because "garbage" does not mean what you think it means in this context. In particular, "garbage" does not mean "random". (Or if it does, it's more in the sense of xkcd 221.)
Computers are usually deterministic. You have to work pretty hard to get truly random behavior. Even a program that contains the worst kind of undefined behavior will quite often return exactly the same strange and indeterminate number every time you run it.
I have used this analogy:
Suppose you go to the store and buy a brand-new garbage can. But it's completely clean! There's no garbage in it at all! It's so clean you could eat out of it! Was this false advertising? Did the store fraudulently sell you a non-garbage can?
See more discussion at these previous questions:
1
2
3
4
5.
(Most of those are talking about the values of uninitialized local variables, not the values of functions that fail to execute a proper return
statement, but the arguments are the same.)