Post-increment and pre-increment within a 'for' loop produce same output
After evaluating i++
or ++i
, the new value of i
will be the same in both cases. The difference between pre- and post-increment is in the result of evaluating the expression itself.
++i
increments i
and evaluates to the new value of i
.
i++
evaluates to the old value of i
, and increments i
.
The reason this doesn't matter in a for loop is that the flow of control works roughly like this:
- test the condition
- if it is false, terminate
- if it is true, execute the body
- execute the incrementation step
Because (1) and (4) are decoupled, either pre- or post-increment can be used.
Well, this is simple. The above for
loops are semantically equivalent to
int i = 0;
while(i < 5) {
printf("%d", i);
i++;
}
and
int i = 0;
while(i < 5) {
printf("%d", i);
++i;
}
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 of i
(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
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = ++i;
}
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = i++;
}
This is because in first block of code j
sees the value of i
after the increment (i
is incremented first, or pre-incremented, hence the name) and in the second block of code j
sees the value of i
before the increment.