This question already has an answer here:
- Difference between i++ and ++i in a loop? 21 answers
The following for loops produce identical results even though one uses post increment and the other pre-increment.
Here is the code:
for(i=0; i<5; i++) {
printf("%d", i);
}
for(i=0; i<5; ++i) {
printf("%d", i);
}
I get the same output for both 'for' loops. Am I missing something?
The third statement in the for construct is only executed, but its evaluated value is discarded and not taken care of.
When the evaluated value is discarded, pre and post increment are equal.
They only differ if their value is taken.
There is a difference if:
The result:
inside post incement = 0
i = post increment in loop 0
inside post incement = 1
i = post increment in loop 1
The second for loop:
inside pre incement = 0
i = pre increment in loop 1
inside pre incement = 1
i = pre increment in loop 2
You could read Google answer for it here: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Preincrement_and_Predecrement
So, main point is, what no difference for simple object, but for iterators and other template objects you should use preincrement.
EDITED:
There are no difference because you use simple type, so no side effects, and post- or preincrements executed after loop body, so no impact on value in loop body.
You could check it with such a loop:
Well, this is simple. The above
for
loops are semantically equivalent toand
Note that the lines
i++;
and++i;
have the same semantics FROM THE PERSPECTIVE OF THIS BLOCK OF CODE. They both have the same effect on the value ofi
(increment it by one) and therefore have the same effect on the behavior of these loops.Note that there would be a difference if the loop was rewritten as
This is because in first block of code
j
sees the value ofi
after the increment (i
is incremented first, or pre-incremented, hence the name) and in the second block of codej
sees the value ofi
before the increment.Compilers translate
to
So in your case (post/pre- increment) it doesn't matter.
EDIT: continues are simply replaced by
goto end;
Yes, you'll get exactly same outputs for both. why do you think they should give you different outputs?
Post-increment or pre-increment matters in situations like this:
where you provide some value, either by assigning or by passing an argument. You do neither in your
for
loops. It gets incremented only. Post- and pre- don't make sense there!