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

前端 未结 9 746
南方客
南方客 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 07:53

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

    #include 
    #include 
    
    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.

提交回复
热议问题