Search code examples
clibcabsolute-value

Why is abs(INT_MIN) still -2147483648?


The result of abs(-2147483648) is -2147483648. This seems incorrect.

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

output:

abs(-2147483648): -2147483648

Solution

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