Why is abs(0x80000000) == 0x80000000?

sigjuice picture sigjuice · Mar 29, 2010 · Viewed 8.2k times · Source

I just started reading Hacker's Delight and it defines abs(-231) as -231. Why is that?

I tried printf("%x", abs(0x80000000)) on a few different systems and I get back 0x80000000 on all of them.

Answer

James McNellis picture James McNellis · Mar 29, 2010

Actually, in C, the behavior is undefined. From the C99 standard, §7.20.6.1/2:

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 its footnote:

The absolute value of the most negative number cannot be represented in two’s complement.