[fpc-devel] Implicit Type Conversion when running with range and overflow checking

Nikolay Nikolov nickysn at gmail.com
Wed Feb 25 10:20:10 CET 2015

On 02/25/2015 01:47 AM, Louis Salkind wrote:
> Pardon the stupid question(s)...  I was surprised by the behavior of 
> the following code when range checking and overflow checking was 
> enabled on win32:
> procedure test_rangeoverflow;
> var
>   a, b: BYTE;
>   i: Integer;
> begin
>   a := 128;
>   b := 129;
>   i := a + b;   // no errors, i is 257; a and b have been promoted to 
> integers
>                 // but shouldn't there be a range check, as a+b has 
> overflowed a byte and should not be promoted?
No, because both are implicitly converted to the natural integer type 
for the platform (32-bit on 32-bit platforms, 64-bit on 64-bit 
platforms, 16-bit on i8086), then the addition is done using that type.
>   i := BYTE(a + b);    // no errors, and i is 1.  Even if a+b is 
> promoted to integer,
>                        // shouldn't there be range check when coercing 
> and integer of 257 to byte?
No, because a typecast to a different integer type explicitly disables 
range checking. IOW, it means "I know what I'm doing, truncate this to a 
byte and just ignore the higher bits." If you want range checking, don't 
use a typecast.
>   a := a + b;    // gives range check when storing result, but not an 
> overflow error first
An overflow error is like a range check error, but is produced when you 
exceed the natural integer size of the processor. So, on a 32-bit 
platform, adding two 32-bit integers may produce an overflow error, 
while adding 16-bit integers may produce a range check error. AFAIK, 
this distinction is done for BP7 and Delphi compatibility reasons, but 
anyhow, you, as a programmer, can think of them as being the same thing.
> end;
> Comments?  I'm guessing this is either specified in the Pascal 
> standard, or fpc is emulating Delphi behavior.  Nevertheless, the 
> result seemed non-intuitive enough to me that I wanted to confirm this 
> was the intended behavior.
I'm not familiar with Pascal standards (although I thing at least 
Standard Pascal has only one integer type, so the standard says nothing 
about mixing different integer types), but this is the BP7 and Delphi 


More information about the fpc-devel mailing list