Sign in Join
Wiki copytemporary

$rangeChecks

The FPC’s local compiler directive {$rangeChecks} enables or disable range checks of ordinal data type expressions, the default being {$rangeChecks off}. The short form {$R+} and {$R-} is recognized too.

range checks

A range check ensures a value is within the domain of the destination operand. As soon as an operand needs to be “squeezed” into a smaller range, the expression or statement is eligible to a range check.

behavior

If a range check fails, the runtime error 201 “Range check error” is generated. Thus the code sample

delphi>
    {$rangeChecks on}
    x := y;
</syntaxhighlight>
is ''semantically'' equivalent to
<syntaxhighlight lang=

   {$rangeChecks off}
   x := y;
   if (x < low(x)) or (x > high(x)) then
   begin
       runError(201);
   end;

(The reported memory address at which the error occurred will differ and the compiler may produce optimized code.)

eligibility

Range checks can be performed

For assignments involving constant expressions a range check is performed already at compile-time, but is either a warning or error depending on the current setting.

placement

The FPC allows enabling and disabling range checks on a per-statement basis, while Delphi allows changing the setting only a per-routine level.

caveats

application

Range checks can incur a significant performance penalty. Therefore, the FPC disables range checks by default. However, at least during development and prior releases of software, range checks should be enabled to find “obvious” programming mistakes. As a consequence of this practice, if a code fragment is meant to exceed the permissible range, it should be documented like this:

delphi>
    {$push}
        {$rangeChecks off}
        x := y;
    {$pop}
</syntaxhighlight>

Use <code>{$ifOpt}</code> if code needs to be different on the current range-check-setting:
<syntaxhighlight lang=

   {$ifOpt R-} // or R+
       …
   {$endIf}


From the Free Pascal wiki, page "$rangeChecks", as it stood on 2022-03-05 after a change by Alextp, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 4, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.