The result of abs(-2147483648) is -2147483648, isn't it? it seems unacceptable.
printf("abs(-2147483648): %d\n", abs(-2147483648));
output:
abs(-2147483648): -2147483648
Negative numbers line up on the left; positive numbers run along the track to the right. So, the number –4.0 is 4 units away from zero. The number –45.3 is 45.3 units away from zero and the number 10 is 10 units away from zero. Therefore, the absolute value of any number is really a positive number (or zero).
Answer: -1 is the greatest negative integer. In a number line, the numbers to the right from 0 (zero) are the positive integers. And, the numbers left to 0 (zero) are the negative integers.
The standard says about abs()
:
The
abs
,labs
, andllabs
functions compute the absolute value of an integerj
. If the result cannot be represented, the behavior is undefined.
And the result indeed cannot be represented because the 2's complement representation of signed integers isn't symmetric. Think about it... If you have 32 bits in an int
, that gives you 232 distinct values from INT_MIN
to INT_MAX
. That's an even number of values. So, if there's only one 0, the number of values greater than 0 cannot be the same as the number of values less than 0. And so there's no positive counterpart to INT_MIN
with a value of -INT_MIN
.
So, what's unacceptable is calling abs(INT_MIN)
on your platform.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With