Cause of Range Check Error (Delphi)

前端 未结 1 1257
忘掉有多难
忘掉有多难 2020-12-07 01:22

Here\'s a condensed version of some code that causes both a Range check error and an overflow error, should I turn on those compiler check directives. I understand why this

相关标签:
1条回答
  • 2020-12-07 01:32

    The documents about range-checking states:

    The $R directive enables or disables the generation of range-checking code. In the {$R+} state, all array and string-indexing expressions are verified as being within the defined bounds, and all assignments to scalar and subrange variables are checked to be within range. If a range check fails, an ERangeError exception is raised (or the program is terminated if exception handling is not enabled).

    So the reason here is the assignment to a scalar value, which is handed a value that has passed the upper range.

    See also docwiki Simple Types about range-checking errors on simple types and subrange types.

    Example:

    {$R+} // Range check on
    var
      w1,w2 : word;
    begin
      w1 := High(word);
      w1 := w1 + 10; // causes range-check error on assignment to w1 (upper range passed)
      w2 := 0;
      w2 := w2 - 10; // causes range-check error on assignment to w2 (lower range passed)
    end;
    

    A summary test of all combinations of $R and $Q for all platform-independent integer types:

                R+Q+  R+Q-  R-Q+
     ShortInt    R     R     x
     SmallInt    R     R     x
     Integer     O     x     O
     LongInt     O     x     O
     Int64       O     x     O
     Byte        R     R     x
     Word        R     R     x
     LongWord    O     x     O
     Cardinal    O     x     O
     UInt64      O     x     O
    

    R=Range error; O=Overflow error; x=Nothing

    And the test was(pseudo-code) with XE2 in 32-bit mode:

    number := High(TNumber);
    number := number + 1;
    
    0 讨论(0)
提交回复
热议问题