Consider the following question, coming from one of Enthuware's mock exams:
What will be the output if you run the following program?
The answer being: 0 0 will be printed followed by 1 1.
I expected the loop not to run at all, and that simply 1 1 would be printed. j has a pre-increment operator (++j), so my assumption was that j will be incremented before the loop checks whether the code within curly brackets should be executed.
However, it appears now that the following is actually happening:
1) j is set to 0.
2) it is checked whether j is less than 1, which is true at this point. The compiler then decides that no matter what, the code within curly brackets will be executed.
3) j is then incremented, but it's too late: the code will be executed.
Is this order of steps correct?
Also, doesn't this mean it essentially doesn't matter whether the update clause of a loop uses pre- or post-increment? The results for i and j are the same, after all.
Shane Jensen wrote:(...) Is this order of steps correct?
At first, i = j = 0. so the code in the curly braces is executed. Then j and i are incremented. Since then j >= 1, the curly code is not executed anymore.
That i j = 1 1 is still being printed, is caused by line 8.