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