Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 331
sigjuice Avatar asked Mar 29 '10 15:03

sigjuice


1 Answers

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.

like image 70
James McNellis Avatar answered Sep 28 '22 17:09

James McNellis