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

前端 未结 9 819
南方客
南方客 2021-01-31 07:38

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         


        
9条回答
  •  半阙折子戏
    2021-01-31 07:53

    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.

提交回复
热议问题