我想了解调用递归函数 'fun' 时 x 的值如何变化

I want to understand how the value of x changes when recursive function 'fun' is called

#include <stdio.h>
int fun(int n)
{
    static int x = 0;
    if (n <= 0)
        return 1;
    if (n>3)
    {
        x =n;
        return fun(n-2)+ 3;
    }
    return fun(n-1)+ x;
}
int main()
{
   return fun(5);
}

我的想法是,当在 main() 函数中调用 fun(5) 时。满足if条件if(n>3)。 'n' 的值 5 由 x =n; 分配给 x。在下一个语句中 return fun(n-2)+3; 将是 fun(3)+3;。所以我感到困惑的地方是,当执行 fun(3) 时,语句 static int x = 0; 之后的值将是“5”或“0”。我假设它在 if 条件块中保持为“5”。静态变量在这些递归函数中的作用。

你的函数

int fun(int n)
{
    static int x = 0;
    if (n <= 0)
        return 1;
    if (n > 3) {
        x = n;
        return fun(n - 2) + 3;
    }
    return fun(n - 1) + x;
}

完全一样
static int x = 0;

int fun(int n)
{
    if (n <= 0)
        return 1;
    if (n > 3) {
        x = n;
        return fun(n - 2) + 3;
    }
    return fun(n - 1) + x;
}

除了前一种情况,x只能在fun.

内部访问