Is there a difference in ++i
and i++
in a for
loop? Is it simply a syntax thing?
To understand what a FOR loop does
The image above shows that FOR can be converted to WHILE, as they eventually have totally the same assembly code (at least in gcc). So we can break down FOR into a couple of pieces, to undertand what it does.
for (i = 0; i < 5; ++i) {
DoSomethingA();
DoSomethingB();
}
is equal to the WHILE version
i = 0; //first argument (a statement) of for
while (i < 5 /*second argument (a condition) of for*/) {
DoSomethingA();
DoSomethingB();
++i; //third argument (another statement) of for
}
It means that you can use FOR as a simple version of WHILE:
The first argument of FOR (int i) is executed, outside, before the loop.
The third argument of FOR (i++ or ++i) is executed, inside, in the last line of the loop.
TL:DR: no matter whether
i++
or++i
, we know that when they are standalone, they make no difference but +1 on themselves.In school, they usually teach the i++ way, but there are also lots of people prefer the ++i way due to several reasons.
NOTE: In the past, i++ has very little impact on the performance, as it does not only plus one by itself, but also keeps the original value in the register. But for now, it makes no difference as the compiler makes the plus one part the same.