LoopBodyScopeImpliesLoopLifetimeDRAFT
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.
Lifetime of variables declared in a loop body extends across all loop iterations
Lifetime of variables declared in a loop body is limited to one loop iteration
CorrectionHere 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?
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.