I’ve this C code which I was sure it wouldn’t work, but it does.
#include <stdio.h>
int* find (int* a, int val) {
if (*a == val)
return a;
else
find(a+1, val);
}
int main() {
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int *b;
b = find(a, 7);
printf("%d\n", *b);
return 0;
}
Of course, I get a warning from gcc since it lacks a return statement inside the else branch of the find function. However, it works perfectly.
Why does this happen? How does it know to return an int through the recursive function? Of course, the last calls returns an int, but I’m calling it in a void context.
Assuming that you meant to write
findinstead oftrova(I knew learning Italian would come in handy some day :), the answer is that this does not work perfectly. It “works” purely by chance, by virtue of undefined behavior.Most likely, the deepest recursive call pushes the return value into some register, which the higher-level calls don’t touch because they don’t have a return statement, and when the caller inspects that register, the return value of the deepest call is still there. You can’t rely on this, though.