Name

$RangeChecks Compiler Directive

Syntax

{$R-}              // default
{$RangeChecks Off} // default
{$R+}
{$RangeChecks On}

Scope

Local

Description

The $RangeChecks directive tells the compiler to generate code that checks array operations to ensure that the array index is within the array bounds. If an index is out of bounds, Delphi reports runtime error 4 (ERangeError).

Tips and Tricks

  • You should always enable the $RangeChecks directive because it can catch numerous errors in your code. A common misconception is that the checks should be disabled in released programs. If an array bounds error occurs, you want to catch the error as soon as possible, and avoid referring to an invalid array location, which can result in memory corruption. Do not disable the range checks unless you have a specific performance problem, and then disable the checks only in the performance-critical parts of your code.

  • Many Internet security breaches are due to array bounds errors. The programs were mostly written in C, which never checks array bounds, but when using Delphi, you have no excuse not to take advantage of the security features that the language offers.

  • When $RangeChecks is enabled, Delphi also checks string references to make sure they are between 1 and the string length, but if a long string is empty, Delphi raises an access violation instead of a runtime error (because Delphi represents an empty string with a nil pointer). Thus, you should always check for an empty string before using a string subscript: ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.