Why use abs() or fabs() instead of conditional negation?

Subhranil picture Subhranil · Feb 4, 2018 · Viewed 13.2k times · Source

In C/C++, why should one use abs() or fabs() to find the absolute value of a variable without using the following code?

int absoluteValue = value < 0 ? -value : value;

Does it have something to do with fewer instructions at lower level?

Answer

Baum mit Augen picture Baum mit Augen · Feb 4, 2018

The "conditional abs" you propose is not equivalent to std::abs (or fabs) for floating point numbers, see e.g.

#include <iostream>
#include <cmath>

int main () {
    double d = -0.0;
    double a = d < 0 ? -d : d;
    std::cout << d << ' ' << a << ' ' << std::abs(d);
}

output:

-0 -0 0

Given -0.0 and 0.0 represent the same real number '0', this difference may or may not matter, depending on how the result is used. However, the abs function as specified by IEEE754 mandates the signbit of the result to be 0, which would forbid the result -0.0. I personally think anything used to calculate some "absolute value" should match this behavior.

For integers, both variants will be equivalent both in runtime and behavior. (Live example)

But as std::abs (or the fitting C equivalents) are known to be correct and easier to read, you should just always prefer those.