for(int i=0 ; i++ ; printf("%d",i));
printf("%d",i);
Output is 1.
If we make i = 1 then there is an absurd output and if i = -1 then the output is 01.
How is the For loop functioning?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The test part of the for-loop is
i++.Because the
++(or increment) is post-fix (written after the variable, instead of before it), the increment happens after the statement is evaluated and tested. The test is on0, which evaluates to FALSE, hence the “loop” exists without ever being run.Next, the post-fix
++takes effect, changingifrom 0 to 1.As @paxdiablo pointed out, once the loop exits,
iis out of scope.Whatever the final printf is printing, it is a different
i, declared and given a value that is not shown in your code.In the other scenarios, if you start
iat 1, then the test is always true, and every number is printed out (untilioverflows, and returns to 0).And finally, if
istarts at -1, the test initially passes (-1 is TRUE), the post-fix increment happens, turning -1 into 0, and 0 is printed out.The loop is run again, this time 0 fails the test, the loop ends, the post-fix increment happens, and the other
i(not shown in your code) is printed out after the end of the loop.