The below writes: -9223372036854775808
Shouldn't absolute return a positive number?
program Project1;
begin
writeln( abs(low(int64)) );
end.
Seems
writeln( abs(low(longint)) );also returns negative...

Mailing lists / fpc-devel / 2024-04
5 messages · 4 people ·
Reply by email Subscribe to this list Your subscription
Read-only archive. Use j and k to move between messages.
The below writes: -9223372036854775808
Shouldn't absolute return a positive number?
program Project1;
begin
writeln( abs(low(int64)) );
end.
Seems
writeln( abs(low(longint)) );also returns negative...
Ahoy, hoy,
Martin Frb wroteThe below writes: -9223372036854775808 Shouldn't absolute return a positive number?
No, see https://wiki.freepascal.org/Integer#characteristics
The below writes: -9223372036854775808 Shouldn't absolute return a positive number?…
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.
Kit
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.
The below writes: -9223372036854775808 Shouldn't absolute return a positive number?…
See https://gitlab.com/freepascal.org/fpc/source/-/issues/40694 There were several commits about Abs w.r.t. this bug lately.