Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a for loop, is there a difference between pre/post-incrementing a loop control variable in terms of the total quantity of iterations?

When I compile and run the code below with either counter++ or ++counter substituted for x, the output is identical; in both cases, numbers 1 - 10:

for (int counter = 1; counter < 11; x)
{
    std::cout << counter << endl;
}

Originally I thought ++counter would increment by 1 and then return the new value before for boolean expression in the loop header was evaluated. i.e when starting with counter = 1 and using ++counter, counter would have a value of 2 in the boolean expression. This appears to not be the case, as both outputs are identical rather than the ++counter version having one less iteration, like I expected.

Reading around, it appears ++counter and counter++ increment counter by 1 at either the start or end of the loop body respectively. In which case is this not, at least conceptually, an identical action? Because the end and the start of the loop are the same thing once the loop has past the first iteration.

The only time I can see this making a difference is in the first iteration, where std::cout << counter << endl;should output 1 to the console if counter++ is used (because 1 is added to counter at the end of the loop). Whilst std::cout << counter << endl; should output 2 to the console if ++counter is used (because 1 is added to counter at the start of the loop).

In addition to the question above, could you please precisely explain the 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.

Many thanks!

like image 772
izaak_pyzaak Avatar asked Feb 08 '15 10:02

izaak_pyzaak


1 Answers

There is no difference. In older compilers, ++counter was faster because it did not create a temporary variable but all modern compilers can optimize that out. For heavy objects with custom (non-inlined) increment operators, ++counter can still be more efficient.

As for when evaluation takes place:

for (initialization; condition; increment/decrement)
    code;

is evaluated as

{
    initialization;
    while (condition)
    {
        code;
        increment/decrement;
    }
}
like image 76
StenSoft Avatar answered Oct 08 '22 09:10

StenSoft