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

前端 未结 9 729
南方客
南方客 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:51

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

    Various reasons have already been stated, yet consider conditional code advantages as abs(INT_MIN) should be avoided.


    There is a good reason to use the conditional code in lieu of abs() when the negative absolute value of an integer is sought

    // Negative absolute value
    
    int nabs(int value) {
      return -abs(value);  // abs(INT_MIN) is undefined behavior.
    }
    
    int nabs(int value) {
      return value < 0 ? value : -value; // well defined for all `int`
    }
    

    When a positive absolute function is needed and value == INT_MIN is a real possibility, abs(), for all its clarity and speed fails a corner case. Various alternatives

    unsigned absoluteValue = value < 0 ? (0u - value) : (0u + value);
    

提交回复
热议问题