Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stack function call problem

Tags:

c

function

i have a function called fun1(), which is used for recursion. I am confused regarding the first call to this fun(--n);. What it will do and how will my stack pop my functions after each function finishes?

void fun(int n)
{
    if(n>0)
    {
        fun(--n);
        printf("%d",n);
        fun(--n);
    }
}

My main function is as below:

    int a;
    a=3;
    fun(a);

I want to know the order of execution and what my stack will contain before, during, and after the function call of the first fun(--n).

like image 844
teacher Avatar asked Dec 16 '22 09:12

teacher


1 Answers

It will print 0120

                                  (3->[2]->1)
                                       +   +
                                       |   |
                          +------------+   +-------+
                          |                        |
                         ({2}->[1]->0)           ({1}->[0]->-1)
                                +   +                        +
                                |   |                        |
                 +--------------+   +----+                   |
                 |                       |                   +
                 |                       |                  (X)
                 +                       +
                ({1}->[0]->-1)          (0->X)
                       +    +
                       |    |
          +------------+    |
          |                 |
          |                 |
          +                 +
         ({0}->X)          (X)

The above is a representation of the call tree. Read like this: The first number in the ( ) , wrapped in { } is the value which the function receives for one call, the next number following an arrow represents the value decreased by one and it is used to call again. The [ ] represents when returning it is printed. The last number in ( ) is the value which is used to the second call after the printf . An (X) represents that it is not able to get into the if block. At the end of each ( ) braces the function returns to the point where it originated from (follow the lines). Note the value gets printed after returning of the first call.

like image 191
phoxis Avatar answered Dec 29 '22 11:12

phoxis