Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does stdlib.h's abs() family of functions return a signed value?

Tags:

c

math

std

The negative implication of this is noted in the man page:

NOTES Trying to take the absolute value of the most negative integer is not defined.

What's the reasoning behind this and what's the best recourse for a person who would like to avoid undefined behavior? Do I have to resort to something like:

unsigned uabs(signed val) {
    return val > 0
        ? val
        : (val == 1U << ((sizeof(val) * 8) - 1))
            ? -1U
            : -val;
}

(Intentionally hacky to emphasize displeasure with stdlib ;-)

Example

Say you had a 4-bit signed value (for ease of understanding). unsigned max is 15, signed (positive) max is 7, signed (negative) min is -8, so abs(-8) won't fit into a signed value. Sure, you can represent it as -8, but then division and multiplication with the result don't work as expected.

like image 772
cdleary Avatar asked Oct 23 '09 01:10

cdleary


People also ask

Does abs return an int?

abs(int a) returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.

What does abs () do in C?

In the C programming language, the use of the function abs in C is to return the absolute value of an integer. By integer, it means that the abs() is an arithmetics function. The stdlib. h library contains predefined function abs() for computing the absolute value of integers.

What is the absolute value function in C++?

The abs() function in C++ returns the absolute value of an integer number. This function is defined in the cstdlib header file. Mathematically, abs(num) = |num| .

What is absolute value in programming?

If you recall, the absolute value of a number is the number "made positive" by dropping the minus sign if the number if negative and just letting the number pass if it's positive. So for example, the absolute value of -3 is 3 and the the absolute value of 3 is 3.


1 Answers

The real answer to this question lies in the type promotion rules.

If I apply an arithmetic operator to an unsigned int and an int, then the int argument is promoted to unsigned, and the result is also unsigned.

If the abs() function returned unsigned, then it would cause this kind of type promotion of other values when it was used in an expression, which would cause unexpected results. For example, this code:

if (abs(-1) * -1 < 0)
    printf("< 0\n");
else
    printf(">= 0\n");

Would print ">= 0", which many wouldn't like. The tradeoff, of not being able to use the single value INT_MIN, presumably seemed OK.

like image 196
caf Avatar answered Nov 15 '22 18:11

caf