DRAFT
LoopBodyScopeImpliesLoopLifetime
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
CorrectionHere is what's right.
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
SymptomsHow do you know your students might have this misconception?
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.