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?
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:
Because (1) and (4) are decoupled, either pre- or post-increment can be used.