The for-loop variable violates the loop limit

Today I met a very strange mistake.

I have the following code:

var i: integer;
...
for i := 0 to FileNames.Count - 1 do
begin
  ShowMessage(IntToStr(i) + ' from ' + IntToStr(FileNames.Count - 1));
  FileName := FileNames[i];
  ...
end; 
ShowMessage('all');

There is one item in the FileNames list. So, I believe that the loop will be executed once, and I see

0 from 0
all

This is what I have done thousands of times :). But in this case, I see the second iteration of the loop when code optimization is enabled.

0 from 0
1 from 0
all

Without a code optimization loop, iterates to the right. At the moment, I don’t even know the direction to move with this problem (and the upper cycle does not change, yes).

Therefore, any suggestion will be very useful. Thank.

I am using the Delphi 2005 compiler (Upd2).

+4
source share
2 answers

QC, LU RD, D2005, . , while while.

1. for while

var
  i: integer;
begin
  i := 0;
  while i < FileNames.Count do
  begin
    ...
    inc(i);
  end;
end;

2.Leave for , , .

var
  ctrl, indx: integer;
begin
  indx := 0;
  for ctrl := 0 to FileNames.Count-1 do
  begin
    // use indx for string manipulation and FileNames indx
    inc(indx);
  end;
end;

3. , Without code optimization loop iterates right. , , ({$ O-}) / ({$ O +}) . ! Optimization /.

+3

, , . , , , NDA. .

dll, . :

type
  TData = packed record
    Count: integer;
  end;
  TPData = ^TData;

, dll:

Calc: function(Data: TPData): integer; stdcall;

, (TList):

var
  i: integer;
  Data: TData;
begin
  for i := 0 to List.Count - 1 do
  begin
    Data := TPData(List[i])^;
    Calc(@Data);
  end;

, , 0 0.

var
  i: integer;
  Data, Data2: TData;
begin
  for i := 0 to List.Count - 1 do
  begin
    Data := TPData(List[i])^;
    Data2 := TPData(List[i])^;
    Calc(@Data2);
  end;

, .

Dll , .

- . BTW, Data Data2 .

, -. , , , .

0

Source: https://habr.com/ru/post/1570903/


All Articles