Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

recursion - How does this C int function works without a return statement?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This code is not a valid C code, and the behavior of such code is not defined.

One reason why it work may be that there is no operation after the last call in find which may result in the return value of the recursive call staying in the return register (probably eax).

But again - the behavior is undefined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...