unexpected output in C (recursion)

2019-01-08 02:36发布

int main(void) {
 static int=5;
 if(--i) {
    main();
    printf("%d",i);
   }
 }

the output of above program is---

0000

But I think it should be---

1234

I dont know why?please help me.

标签: c recursion
2条回答
乱世女痞
2楼-- · 2019-01-08 02:53

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).

查看更多
冷血范
3楼-- · 2019-01-08 03:05
  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

查看更多
登录 后发表回答