[fpc-pascal]Re: "for" loop questions
XHajT03 at mbox.vol.cz
XHajT03 at mbox.vol.cz
Sun Dec 8 10:21:19 CET 2002
From: "Balogh, Karoly (Charlie/iNQ)" <charlie at scenergy.dfmk.hu>
To: fpc-pascal at deadlock.et.tudelft.nl
Date sent: Sun, 08 Dec 2002 08:50:51 +0100
Subject: [fpc-pascal]Re: "for" loop questions
Send reply to: fpc-pascal at deadlock.et.tudelft.nl
Hi,
> > 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.
I 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.
> > 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
More information about the fpc-pascal
mailing list