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

Victor S picture Victor S · Jun 28, 2012 · Viewed 19.5k times · Source

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

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

output:

abs(-2147483648): -2147483648

Answer

Alexey Frunze picture Alexey Frunze · Jun 28, 2012

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.