Range Checking

In some compilers, particularly older ones such as Delphi 7, range checking of arrays is turned off by default. You would be forgiven for expecting that the following tiny program would not compile.

program ArrayErrors;
  {$APPTYPE CONSOLE}
uses
  SysUtils;
var
  ArrayFirst : array[1 .. 2] of integer =  (10, 20);
  ArraySecond : array[1 .. 2] of integer =  (30, 40);
  Index : integer = 3;
begin
  writeln(ArrayFirst[Index]);
  writeln(ArrayFirst[Index + 1]);
  writeln(ArraySecond[Index - 3]);
  readln;
end.

It does compile in Delphi 7, and produces this output:

Output from Delphi 7

Output from Delphi 7

In each case the index is beyond the bounds of the array and the program is reading from the wrong array the data to output. The program also compiles in the latest version (0.9.30) of Lazarus and produces the following output:

Output from Lazarus

Output from Lazarus

If we turn on range checking we obtain the expected error message from the compiler. Shown here for Delphi 7, with the compiler directive {$R+} ...

Compiler directive for range checking

Compiler directive for range checking

we obtain this error message:

Output

Output

Attempting to read beyond the bounds of an array is a common error. We hope that the above will convince you that sometimes you can reduce the time spent debugging if you turn on range checking in the debug version of your program. (You will have noticed that we have used {$R+} in some of our examples).

Programming - a skill for life!

Stepping through code, setting breakpoints, error handling and range checking