[fpc-pascal] subtract longwords with rollover

Tomas Hajny XHajT03 at hajny.biz
Thu Nov 28 17:59:58 CET 2013

On Thu, November 28, 2013 17:37, Klaus Hartnegg wrote:


> How can I subtract two longwords such that when the result becomes
> negative, it rolls over?
> A := A - B triggers runtime error 201 when the result is negative.
> dec (A,B) rolls over, but triggers runtime error 201 when A is higher
> than the highest possible value of longint.
> Is dec only declared for longint, but not for longword?
> dec(longint(A),B) fails when the result is larger than 2 billion.
> I cannot use longint instead of longword, this causes problems in other
> parts of the code.

Both A := A - B fail only if you compile with range checking on and you
try to assign a negative value to an unsigned type (which is obviously
fully correct behaviour, because you indeed cross the defined range of the
respective type). This implies several possible options:

1) Compile with range checking off (-Cr-). ;-)

2) Disable range checking for the respective part of your code (put
{$RANGECHECKS OFF} and {$RANGECHECKS ON} around either "A := A - B" or
"Dec (A, B)").

3) Perform an explicit typecast of your (negative) result to the type of
the target variable ("A := longword (A - B)").


More information about the fpc-pascal mailing list