简体   繁体   中英

Can anyone explain output of this program

static variable example with recursion function

 #include <stdio.h>
    int main()
    {
        static int i=10;
        if(--i)
        {
            main(); /*recursive call main */
            printf("%d ", ++i); /* print returned value of main */

        }
    }

While i is not equal to zero the function main calls itself.

    if(--i)
    {
        main(); /*recursive call main */

So you have a chain of calls

main( i = 10 ) -> main( i = 9 ) ->...-> main( i = 0 )

When i is equal to zero then the recursion stops and each called main returns the control to the previous call of main.

The previous call of main just execute this statement

printf("%d ", ++i); /* print returned value of main */

Thus the output will be

1 2 3 4 5 6 7 8 9

++i is the same as i = i + 1 so when you write

printd("%d ", ++i);

you increment i again so its value stays the same.

static variable is initialized once. And its lifetime is of the program. As variable is initialized once, it will have initial value of 10.

In every recursive call, it will be decremented (at if statement) and when reached to 0, it will not recur further.

After the last recursion, it will start printing and return.

As printf statement is after recursion, it will start first printing after last recursion (when i=1 ) and will print 1 to 9.

While executing printf and returning, it will keep increasing i by 1. Hence, topmost function stack will get i as 9.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM