2

In the abs's man manual, there's a NOTES: Trying to take the absolute value of the most negative integer is not defined.

And the prototype of abs is:int abs(int j);

Why does abs return int? As the return value will be positive, why not return unsigned int?

If abs returned unsigned int, the solution of the most negative integer's absolute value is simple like this:

if(INT_MIN == j) 
  return (unsigned int)j; 
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
jacob
  • 671
  • 6
  • 15

2 Answers2

4

There are a variety of issues in mixing signed and unsigned values in calculations, so the question would be: What are most users going to do with the result of calling abs(int)? I think the most likely answer - or at least a very common one - is that they'll do further arithmetic with the result. In that case, you almost surely want to stay within int rather than getting back an unsigned.

Here's another post on mixing signed with unsigned in calculations: what happens when i mix signed and unsigned types ?

Community
  • 1
  • 1
Brick
  • 3,998
  • 8
  • 27
  • 47
-2

A 16 bit signed integer has a range of -32768 to +32767

So INT_MIN will be -32768. The absolute value of that is outside the range of an integer. Therefore it is not defined.

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31