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
", *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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…