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

前端 未结 5 1993
悲哀的现实
悲哀的现实 2020-12-03 05:14

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

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

out

5条回答
  •  时光说笑
    2020-12-03 05:36

    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.

提交回复
热议问题