PreIncrementBeforeLoop
DRAFT

Misconception:

Using a ++ pre-increment operator in a for loop’s update part, e.g., for (...; ...; ++i) ..., means that the increment happens before the loop body executes, while using a ++ post-increment means that the increment happens after the loop body executes.

Incorrect

Pre-increment in update part of for loop means increment before loop body

Correct

Pre-increment in update part of for loop means same as pre-increment anywhere else

Correction
Here is what's right.

Students incorrectly believe that:

for (int i=0; i<2; ++i) {
  print(i);
}

is equivalent to:

int i=0;
while (i<2) {
  ++i; // incorrect!
  print(i);
}

This is wrong!

The correct meaning of the above for loop is:

int i=0;
while (i<2) {
  print(i);
  ++i;
}

The ++i still happens after the end of the loop body. This code will print 0 and 1. It is no different from this:

for (int i=0; i<2; i++) {
  print(i);
}

The ++ happens before or after the value of i is read. In both cases above, the value of i is read, but is thrown away (i.e., it is not assigned to anything, like with a=i++, and it is not passed to anything, like with m(i++)).

In this misconception, students essentially extend the meaning of “pre” beyond the expression and to the scope of the entire loop.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.