为什么这里需要在函数中有 if 语句才能工作?

Why is needed here to have if statements in the function in order to work?

当我尝试在 C 中使用递归实现斐波那契数列时,我注意到在我的函数 fibo 中,如果我没有使用某种 if 语句 return 1 out of the function the program crashed.Why 是这样吗?

#include<stdio.h>

int fibo(int);
int main(void){
    int n, num;

    scanf("%d", &n);

    num = fibo(n);
    printf("apo: %d", num);
    return 0;
}


int fibo(int n){
    if(n==0)
        return 0;
    else if(n==1)
        return 1;
    else if(n!=0){
        n = fibo(n-1) + fibo(n-2);
    return n;
    }
}


/*FOR EXAMPLE if I leave the fuction like this, it doesn't work*/
int fibo(int n){
        n = fibo(n-1) + fibo(n-2);
    return n;
}

让我们以最简单的递归函数为例。

int foo(int n) 
{ 
    return foo(n-1); 
}

如果你想计算foo(5)那么函数foo需要在返回前计算foo(4)。但 foo(4) 也是如此。它必须首先计算 foo(3) 。所以 n 在函数不需要调用自身的地方没有价值,因此无限递归。理论上是这样的。在实践中它会崩溃。

那些不会引起递归调用的情况称为基本情况

你的函数需要一个限制(基本情况)不再执行它自己,如果你没有语句"if"来决定什么时候跳出函数,你的下面的程序就不能被执行。并且该函数不会停止执行,直到您的程序崩溃。