Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

unexpected output in C (recursion)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...