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

前端 未结 9 717
南方客
南方客 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 08:00

    The intent behind abs() is "(unconditionally) set the sign of this number to positive". Even if that had to be implemented as a conditional based on the current state of the number, it's probably more useful to be able to think of it as a simple "do this", rather than a more complex "if… this… that".

提交回复
热议问题