0

Can anyone explain why 4 zeros are printing by this code ?

#include <stdio.h> int main() { static int i = 5; if(--i){ main(); printf("%d", i); } return 0; } Anyone explain step by step what's happening in the code

12th Nov 2019, 3:49 PM
Preity
Preity - avatar
6 Answers
+ 3
Static retains it's value during function calls as I already mentioned in one of your previous posts. Now see if(4) main() is called, then if(3) main() is called again and similarly happens till if(1) and main() is called. Next time i becomes 0 so the if fails but when you check your stack memory there would be 4 main() calls placed. So now when they are popped out, the printf executes and the i will return 0 because that is the final value it retains. Correct me if I'm wrong.
12th Nov 2019, 4:01 PM
Avinesh
Avinesh - avatar
+ 2
Let's break it down step by step like you said. 1) program starts. It sets i to 5. 2) it decreases i by 1 and check if it's zero. 3) it's not zero so it goes to next line. It calls function main(). 4) So the next line is again static int i = 5; but as i is static this line basically does nothing this time. (doesn't change i) 5) it again decreases i by 1 abd checks if it's 0. No so it executes next line which is again to call main(). This continues until i equals 0. When I becomes zero body of if conditon doesn't execute so the next line is return 0; so program returns to where it was called. Which line number 4 main() ;. The next line is printf i. i is 0 so it prints a zero. It then goes to next line which is again return 0; As you can see this continues. That's why you are getting four 0s.
12th Nov 2019, 4:01 PM
__IAS__
__IAS__ - avatar
+ 1
Program flow of execution: Static i=5( static only ones initialization, and retains value throwout program, with changes) Line1: main() //initial 0 th if( --i )=>i=4 =>main() // 1st i=3 => main() //2nd i=2 => main() // 3rd i=1 => main() //4th [ i=0; //if block not executed , next is return 0; ] // 4 th main() completed ) // goes control to after next statement of main call that is printf, now i =0 so in 3rd main execution,. prints i value 0.. printf(i=0) return 0: // 3rd main() completed. printf(i=0) return 0 //2nd main() completed printf(i=0) return 0; 1st main() call completed. printf(i=0) return 0 // initial 0th main() finished..
12th Nov 2019, 4:31 PM
Jayakrishna 🇼🇳
+ 1
Avinesh you are correct only, But you explained in program terms. If iam a beginner, i may not know what is stack counter there. And question is y 4 times zeros. So i thought to explain step by step. thats simplifies understanding. This question was difficult for me when i first time needed to answer. what i analyzed then, i specified here.
12th Nov 2019, 5:00 PM
Jayakrishna 🇼🇳
0
Jaya krishna Have I answered the question correctly?
12th Nov 2019, 4:39 PM
Avinesh
Avinesh - avatar