Post-increment and pre-increment within a 'for' loop produce same output

theReverseFlick picture theReverseFlick · Jan 16, 2011 · Viewed 203.3k times · Source

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?

Answer

danben picture danben · Jan 16, 2011

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:

  1. test the condition
  2. if it is false, terminate
  3. if it is true, execute the body
  4. execute the incrementation step

Because (1) and (4) are decoupled, either pre- or post-increment can be used.