0

Variable read after for-loop

il2 9 years ago updated 9 years ago 1

This is biggest mistake to count on last value of for-loop variable after the loop:

procedure Test;
var i: Integer;
begin
for i:= 1 to 5 do
Writeln(i);
Writeln(i);
end;


It seems you can count on intermediate value on Break

for i:= 1 to 5 do
if i mod 3 = 0 then Break
else Writeln(i);
Writeln(i);

But this is undocumented, you should know if Break was executed and both cases are too danger to rely on due to optimization which can suddenly use a register for loop var.


This is inspired by Peganza Pacal Expert rules.

Delphi itself produces warning

[dcc32 Warning] W1037 FOR-Loop variable 'i' may be undefined after loop

But adding this check to FixInsight still brings a lot of value.


Btw, Delphi doesn't warn against reading loop-var after loop with Break. Even such case goes unnoticed:

for i:= 1 to 5 do
if False then Break
else Writeln(i);
Writeln(i);