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

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

    Consider that you could feed a complicated expression into abs(). If you code it with expr > 0 ? expr : -expr, you have to repeat the whole expression three times, and it will be evaluated two times.
    In addition, the two result (before and after the colon) might turn out to be of different types (like signed int / unsigned int), which disables the use in a return statement. Of course, you could add a temporary variable , but that solves only parts of it, and is not better in any way either.

提交回复
热议问题