[fpc-pascal] Range checking in a for loop

David W Noon david.w.noon at ntlworld.com
Mon Oct 25 13:24:54 CEST 2010


On Mon, 25 Oct 2010 01:06:16 -0700 (PDT), leledumbo wrote about
[fpc-pascal] Range checking in a for loop:

[snip]
>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.

There is no reason in the for-loop construct that "i" cannot have the
value 4; it is only a problem when "i" is used as a subscript on the
array "a".

Try declaring
   i : 1..3;
instead, as that range matches the array's bounds.  You should then get
a range check at compile time.  It is also the idiomatic Pascal way of
doing this.
-- 
Regards,

Dave  [RLU #314465]
=======================================================================
david.w.noon at ntlworld.com (David W Noon)
=======================================================================
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: not available
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20101025/45647293/attachment.sig>


More information about the fpc-pascal mailing list