Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2016-10

Using for-loop index variable after loop

5 messages · 4 people · –

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Juha Manninen

I have always avoided using a for-loop index variable after the loop. I thought its value can be unpredictable in some situations when the compiler reuses its register or memory etc.

I noticed the ActionListEditor in Lazarus sources has code that uses it after the loop.
The compiler, FPC 3.0, does not warn about it.
I made a small test:

procedure MyProcedure;
var
  i: Integer;
begin
  for i := 0 to 5 do
    WriteLn('iii ', i);
  Write('After loop i=', i);
  if i = 5 then
    WriteLn(' as expected')
  else
    WriteLn(' which is unpredictable');
end;

Indeed, no warning!
Is it OK to do that? Have I misunderstood it?

Juha

Vojtěch Čihák

Hi, if you mean this:
 
function CategoryIndexOf(Name: String): Integer;
  var
    i: Integer;
  begin
    for i:= lstCategory.Items.Count-1 downto 0 do begin       if lstCategory.Items[i] = Name
      then Break;
    end;
    Result := i;
    if (i = lstCategory.Items.IndexOf(cActionListEditorUnknownCategory))        and (i = lstCategory.Items.IndexOf(cActionListEditorAllCategory))     then Result := 0;
  end;
 
It can IMO cause random and hardly reproducible bugs.  
V.
______________________________________________________________

Show quoted text 5 lines
Od: Juha Manninen Komu: FPC-Pascal users discussions Datum: 10.10.2016 12:16 Předmět: [fpc-pascal] Using for-loop index variable after loop

I have always avoided using a for-loop index variable after the loop. I thought its value can be unpredictable in some situations when the compiler reuses its register or memory etc.

I noticed the ActionListEditor in Lazarus sources has code that uses it after the loop.

Juha

Juha Manninen
to Vojtěch Čihák
Vojtěch Čihák wrote
Hi, if you mean this: ...

Yes, that is one of them.
The code does not make sense in any case, regardless of "i"'s value. Index for cActionListEditorUnknownCategory and
cActionListEditorAllCategory differ.
"i" cannot have both at the same time. Maybe the condition should be "or", not "and".
Why does it not compare Name directly with
cActionListEditorUnknownCategory and cActionListEditorAllCategory constants?

There are many similar fishy code blocks. I will sanitize some of them ...

Juha