When I compile and run the code below with replacing counter++ or ++counter with x , the output is identical; in both cases, the numbers 1 - 10:
for (int counter = 1; counter < 11; x) { std::cout << counter << endl; }
Initially, I thought ++counter would increment by 1, and then return a new before value to evaluate the boolean expression in the loop header. that is, starting with counter = 1 and using ++counter , counter will have a value of 2 in a boolean expression. This does not seem to be the case, since both outputs are identical, not the ++counter version, which has another iteration, as I expected.
When read, ++counter and counter++ increment counter appear at 1 at the beginning or end of the loop body, respectively. In this case, is it, at least conceptually, an identical action? Because the end and the beginning of the cycle are one and the same as soon as the cycle has passed the first iteration.
The only time I see that it matters is the first iteration, where std::cout << counter << endl; should output 1 to the console if counter++ (because 1 is added to the counter at the end of the loop). While std::cout << counter << endl; should output 2 to the console if ++counter (because 1 is added to the counter at the beginning of the loop).
In addition to the question discussed above, could you please explain the exact order in which the three actions are evaluated in the for loop header and explain exactly where the iterations occur when using i++ and ++i .
Thank you very much!
source share