为什么不返回语句结束c中的递归函数?

时间:2017-10-24 22:30:32

标签: c recursion return

以下是我正在使用的代码:

#include <stdio.h>

int f_b(int n, int a[n]);

int main() {
    int a[4] = { 7, 6, 5, 4 };
    printf("\n return: %d \n", f_b(4, a));
}

int f_b(int n, int a[n]) {
    int m;
    if (n == 1)
        return a[0];
    m = f_b(n - 1, a);
    printf("m:%d", m);
    if (m > a[n - 1]) {
        printf("\n m was greater than the last item\n ");
        return a[n - 1];
    } else
        return m;
}

这是它给出的输出:

m:7
m was greater than the last item
m:6
m was greater than the last item
m:5
m was greater than the last item

return: 4 

我原本以为第一个f_b之后的printf中的代码块无法访问,因为递归部分会一直倒计时,直到n1为止,with将返回数组的第一项。我假设代码在返回最后一个值之前不会超过m = f_b(n-1, a);行,然后继续执行if - else语句。它似乎会经历if - else每个递归调用?

我注意到每次都没有返回数组的第一项,这促使我用printf语句乱丢函数。我不明白如果还有一个return a[n-1]语句我会假设跳出函数,那么“m大于最后一项”的行怎么可以达到这么多次。我知道它跳出了每个递归调用但是为什么它在完成递归调用时不会总是返回a[0]

请在这里纠正我的想法,因为输出(如我所见)演示了一个return语句,但也被传递。由于递归,是否达到了这么多次?如果是这样,最终会停止代码的是什么(因为n可以无限期地倒计时)

1 个答案:

答案 0 :(得分:2)

每次递归调用函数都有一个返回值,稍后调用返回不会跳出到main的递归,它只是跳转到上一次调用。这就是它可以达到多个返回语句的方式。

当每个调用在堆栈上解析时,函数将通过其余代码完成,这就是我们如何到达递归调用之后的代码(在f_b中)

如果我没弄错的话,这个函数会返回数组中的最小值。