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

Matt Emson memsom at interalpha.co.uk
Sun Dec 8 11:27:10 CET 2002

> Really? Think again... ;)

No, that *is* a bug.

Pascal for loops only run from smallest to largest (fact) when using 'to'.
To run in reverse you *have* to use 'downto'.

Think about it... Integer is a signed value. It can hold negative values. If
List.count = 0 then List.count -1 is equal to -1. For i := 0 to -1 do ;
should never execute. For i := 0 downto -1 do ; *will* execute. This is very
basic Pascal. It's certainly true in Delphi, and you can find countless
occrrence within the VCL for this assumption.

> > 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.

TList.Count returns an Integer in the VCL. If it doesn't in FPC, this is a
bug. Even if it did, you should be able to upcast the value to in integer or

You might thing that adding in the extra line is a safe guard, but then it
actually slows the operation down. Writing optomized code is prefereable to
unessesary code.


More information about the fpc-pascal mailing list