0 votes 0 votes Need Explanation for this question: int main() { static int i=5; if(--i) { printf("F=%d\n",i); main(); printf("Hai\n"); printf("%d\n",i); } } Output: F=4 F=3 F=2 F=1 Hai 0 Hai 0 Hai 0 Hai 0 dinesh4756 asked Sep 23, 2018 dinesh4756 447 views answer comment Share Follow See all 4 Comments See all 4 4 Comments reply sakharam commented Sep 23, 2018 reply Follow Share If you dont know how static variables work: https://www.geeksforgeeks.org/static-variables-in-c/https://www.geeksforgeeks.org/static-variables-in-c/ i is static so its lifetime is as long program is under execution and scope is the function/ block it is declared in. Also I can see that in if() its --i and not -i Initially i=5 Since --i = --5 =4 is not zero value of F=4 is printed. main is called Since i is static, i's value is 4 and not 5. i=4, Similarly i is decremented to 3 F=3 is printed and main() called i=3, Then F=2 and main called i=2, F=1 and main called i=1, Now, in if() i is first decremented to 0 now since its not equal to 0 block of if not executed and function returned. Now i's value is 0 and after main is executed, the statements after it are executed and note that since value of i is not manipulated later all function has i=0. And later following is printed: Hai 0 Hai 0 Hai 0 Hai 0 1 votes 1 votes dinesh4756 commented Sep 23, 2018 reply Follow Share Thanks for the reply. I am confused of why "hai" and "0" prints 4 times? Moreover main(); function call is within if() block, as if() block was not satisfied for i=0 how comes the print of hai and 0 happens? Kindly help me getting this out. Thanks in Advance! 0 votes 0 votes sakharam commented Sep 23, 2018 reply Follow Share 1) Initially main is called when i=5, i decremented to 4, for this hai will be printed after 2) executes 2) main is called, i=4, i decremented to 3, for this hai will be printed after 3) executes 3) main is called, i=3, i decremented to 2, for this hai will be printed after 4) executes 4) main is called, i=2, i decremented to 1, for this hai will be printed after 5) executes 5) main is called, i=1, i decremented to 0, and if not executed hence hai not printed. --5 is executed so hai and 0 printed for 4) once --4 is executed so hai and 0 printed for 3) twice --3 is executed so hai and 0 printed for 2) thrice --2 is executed so hai and 0 printed for 1) four times --1 is executed so program terminated. So total four times hai and 0 is printed 0 votes 0 votes dinesh4756 commented Sep 23, 2018 reply Follow Share Thanks a lot for the detailed explanation. 0 votes 0 votes Please log in or register to add a comment.