[fpc-devel] wrong result for abs(low(int64))

Martin Frb lazarus at mfriebe.de
Thu Apr 4 17:09:26 CEST 2024


On 04/04/2024 16:39, J. Gareth Moreton via fpc-devel wrote:
> Essentially, an arithmetic overflow is happening.  Since the largest 
> Int64 possible is 9,223,372,036,853,775,807, going one above that (the 
> result to abs(low(int64))) wraps back around to 
> -9,223,372,036,853,775,808.
>
> Internally, you can think about negating (positing?) a negative number 
> as inverting the bits and then adding one (aka. two's complement), so 
> low(int64) is 1000...000, which inverted becomes 0111...111, and then 
> adding one results in 1000...000 again.

I got that bit...

Initially I was surprised to find "abs" to return a signed number. After 
all, it will never be negative.

But, in the meantime I recalled that unsigned numbers will cause other 
issues when used in expressions.
"abs(-1)-2" would behave different.


More information about the fpc-devel mailing list