[fpc-pascal] Range checking in a for loop
Paul Ishenin
webpirat at mail.ru
Mon Oct 25 13:26:49 CEST 2010
25.10.2010 16:06, leledumbo wrote:
> Consider the following program:
>
> program test;
>
> var
> a: array [1..3] of Integer;
> i: Integer;
> begin
> for i := 1 to 4 do
> a[i] := i;
> end.
>
> The compiler will accept this code happily, despite the fact that there's an
> out of bounds array index when i = 4.
>
> Since the behavior of for loop in FPC (at least in non Delphi / TP mode) is
> deterministic, it should be possible to check whether the index is out of
> bounds or not. Isn't it? Or is there any situation where it's not?
a[i] is an expression. You can write a[(i+j)/n] there and compiler will
fail to calculate whether the expression match the bound in this case.
Moreover, to create a dynamic array you usually use ^a[0..0] type and it
would be sad if compiler rejected any index <> 0 for this case.
Anyway, if you want to be sure you are in array bounds just use Low(a)
as the lower bound and High(a) as the high bound.
Best regards,
Paul Ishenin.
More information about the fpc-pascal
mailing list