From: "Balogh, Karoly (Charlie/iNQ)"
To:
Date sent: Sun, 08 Dec 2002 08:50:51 +0100
Subject: [fpc-pascal]Re: "for" loop questions Send reply to:
Hi,
Show quoted text 20 lines
> 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 just tried it. If I just add "{$MODE DELPHI}" and "uses Classes;"
at the beginning, and change your final semicolon to period, I don't get any error message - the loop does _not_ execute. At least this is true with my 1.0.7 snapshot compiled November 20. So it works correctly.
Show quoted text 8 lines
> 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.
This isn't really correct either; this would only be true if you assign the result of subtraction to an unsigned variable; the calculation itself is done after conversion to a signed type.
And this is why you get an exception.
Not really, see above. The exception doesn't seem to come from the quoted code fragment (unless you've used some other compiler version and there's some bug in that particular version).
Tomas