Search code examples
cvariablesscopelifetimestatic-variables

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);
}

How i am thinking is that when in the main() function fun(5) is called. It satisfies the if condition if(n>3). The value of 'n' which is 5 is assigned to the x by x =n;. In the next statement return fun(n-2)+3; will be fun(3)+3;. so where am i getting confused is that when fun(3) is executed will the value of be '5' or '0' after the statement static int x = 0;. I assumed it stays '5' in the block of if condition. How static variables act in these kind of recursive functions.


Solution

  • Your function

    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;
    }
    

    works exactly like

    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;
    }
    

    except that in the former case, x can only be accessed inside fun.