[fpc-pascal]Re: "for" loop questions

Balogh, Karoly (Charlie/iNQ) charlie at scenergy.dfmk.hu
Sun Dec 8 08:50:51 CET 2002


Hi,

On 02.12.08., support at falconsoft.com wrote:

> I have a question regarding for loops.  If you execute the following code:
> 
> var
>  L : TList;
>  P : Pointer;
>  I : Integer;
> begin
>  L := TList.Create;
> 
>  for I := 0 to L.Count - 1 do begin
>    P := L[I];
>  end;
> end;
> 
> You get an exception telling you that the list index is out of bounds. 
> L.Count returns "0", but the loop still executes (or at least, it tries
> to) once, which is incorrect.  According to every language I've ever used,
> if L.Count is 0 the first time, the loop should never execute at all.

Really? Think again... ;)

> Is this a bug, or am I missing something?  Of course the fix is to just
> put an "if L.Count > 0" before the "for" loop, but that's not the point -
> the point is I shouldn't have to.  :)

But you should. :) I don't know the type of L.Count, but i suppose it's
unsigned. If L.Count is 0, and you try to count until L.Count-1, it
it simply underflows at the -1 operation. And i will count to $FF, $FFFF
or $FFFFFFF, or whatever, depending on the type of L.Count. 

And this is why you get an exception.

Bye,
-- 
Charlie/iNQ
.:%[ Cybernetic Hydraulic Android Responsible for ]%:. 
.:%[    Logical Infiltration and Exploration      ]%:.
.:%[         Member of TeamOS/2 Hungary           ]%:.
.:%[     Member of Hungarian Amiga User Group     ]%:.





More information about the fpc-pascal mailing list