Unexpected output of the main function by repeated call

后端 未结 1 2009
我在风中等你
我在风中等你 2021-01-29 07:14

I am executing a code written in C and it is giving unexpected result which I could not able to figure it out. Why is the value of I printing five times?

Here is

相关标签:
1条回答
  • 2021-01-29 07:51

    There's nothing wrong with the output.

    • You first set i = 0.
    • the first if(i<5) passes, so i is being incremented (note: i++ means i is still 4, but when its next used the value is 5).
    • Call to main, the static variable i and count keep their values as static variables are not being overwritten, that way the programm passes if(i<5) until i = 5, then if(i<5) returns false and the fifth call to main ends abruptly.
    • Since in the fifth call to main nothing happens, the value of i is now still 4, but since you incremented i via i++, i in printf() is now 5 as this is the time i is being used first after the incremention. Printf shows:

      5
      
    • count is getting incremented via ++count (++count means the value is instantly incremented, so count is now 1). Printf shows:

      1
      
    • Now the recursive loop ends. For each "level" the line

      main();
      

      is done calling, so the next line is

      printf("%d\n", i);
      

      since we never change the value of i anymore (because for all "levels" we already incremented i up to 5), the console shows us 5 times the value of 5 for variable i.

    • The only thing we still change though is the variable count. Since the variable count is still being incremented AFTER the recursive call to main, count still adds up to 5. So the output looks like this:

      5 (i, level 5)
      1 (count, level 5)
      5 (i, level 4)
      2 (count, level 4)
      5 (i, level 3)
      3 (count, level 3)
      5 (i, level 2)
      4 (count, level 2)
      5 (i, level 1)
      5 (count, level 1)
      
    • When count reached 5, we reached the "top" level of our recursive call stack again and the programm ends.
    0 讨论(0)
提交回复
热议问题