LoopBodyScopeImpliesLoopLifetime
DRAFT

Misconception:

Declaring a variable in a loop body means that its lifetime extends throughout all iterations of the loop. If we store a value in that variable in one iteration, this value will still be there in the next iteration.

Incorrect

Lifetime of variables declared in a loop body extends across all loop iterations

Correct

Lifetime of variables declared in a loop body is limited to one loop iteration

Correction
Here is what's right.

The lifetime of a variable declared in a loop corresponds to one iteration only, not to all iterations of the loop.

for (int element : array) {
  int sum = 0;    // sum gets freshly initialized in each iteration
  sum += element; // here sum == 0, and we just add the current element
                  // here sum == element, always
}
// here sum doesn't exist anymore

Symptoms
How do you know your students might have this misconception?

Students with this misconception may declare an accumulator variable inside the loop body, like this:

for (int element : array) {
  int sum = 0;
  sum += element;
}

They might believe that sum gets initialized to 0 in the first iteration, that in subsequent iterations sum just gets incremented, and that after the loop, sum contains the accumulated total.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.