In C/C++, why should one use abs()
or fabs()
to find the absolute value of a variable without using the following code?
int absoluteVal
There might be a more-efficient low-level implementation than a conditional branch, on a given architecture. For example, the CPU might have an abs
instruction, or a way to extract the sign bit without the overhead of a branch. Supposing an arithmetic right shift can fill a register r with -1 if the number is negative, or 0 if positive, abs x
could become (x+r)^r
(and seeing
Mats Petersson's answer, g++ actually does this on x86).
Other answers have gone over the situation for IEEE floating-point.
Trying to tell the compiler to perform a conditional branch instead of trusting the library is probably premature optimization.