unexpected output in C (recursion)

前端 未结 3 1582
迷失自我
迷失自我 2020-11-28 00:03
int main(void) {
 static int=5;
 if(--i) {
    main();
    printf(\"%d\",i);
   }
 }

the output of above program is---

0000

But I t

相关标签:
3条回答
  • 2020-11-28 00:38
    1. You set a static variable i to 5
    2. You recurse on main until i becomes zero.
    3. The recursion unwinds with i being zero.
    4. This then calls the printf

    There lies the answer.

    You can prove this by using a debugger

    0 讨论(0)
  • 2020-11-28 00:40
      [First call:  i->4 and call main()]
      [Second call: i->3 and call main()]
      [Third call:  i->2 and call main()]
      [Fourth call: i->1 and call main()]
      [Fifth call:  i->0 and condition false as it gives 0.]
    

    Now it's time for the printing of value of i, which was the next line after main(). Control go back to fourth to first call to print value of i.

    [Fourth Call: printing value of i which is 0.]
    [Third call:  printing value of i which is 0.]
    [Second call: printing value of i which is 0.]
    [First call:  printing value of i which is 0.]
    
    0 讨论(0)
  • 2020-11-28 00:42

    The reason for the zeros is that i is decremented down to zero before the very first printf statement is run. As it unwinds, it prints i (which is still zero) each time.

    It would be better to use a separate function that main() calls and passes a parameter to (and then pass the parameter to each call rather than using a static variable).

    0 讨论(0)
提交回复
热议问题