Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the absolute value of the max negative integer -2147483648 is still -2147483648?

Tags:

The result of abs(-2147483648) is -2147483648, isn't it? it seems unacceptable.

printf("abs(-2147483648): %d\n", abs(-2147483648)); 

output:

abs(-2147483648): -2147483648 
like image 922
Victor S Avatar asked Jun 28 '12 10:06

Victor S


People also ask

Why is the absolute value of a negative integer is a positive integer?

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).

What is the maximum negative integer?

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.


1 Answers

The standard says about abs():

The abs, labs, and llabs functions compute the absolute value of an integer j. 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.

like image 156
Alexey Frunze Avatar answered Sep 17 '22 17:09

Alexey Frunze