Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute value calculation

When calculating the absolute value of an integer or a floating point value, is there any advantage of using abs from stdlib.h or fabs from math.h compared to using the conditional operator?

#define ABS(x) (((x) >= 0)? (x): -(x))
like image 270
August Karlstrom Avatar asked Aug 23 '16 10:08

August Karlstrom


1 Answers

Code should use abs() with int (or narrower), fabs() with double, fabsf() with float, labs(x) with long, etc. @Joachim Pileborg

  1. Advantage: non-macro. Macro ABS() evaluates the argument twice, likely not desired as in ABS(x++). @EOF and @EOF

  2. Advantage: non-macro. Sequence point definitiveness. @EOF

  3. Advantage: non-macro. -0.0 returns -0.0 with OP's ABS(). fabs(-0.0) returns 0.0. if following IEC 60559 floating-point arithmetic.

  4. Advantage: non-macro. ABS(0.0/0.0) attempts to change the sign. (Corner case concern).

  5. Advantage: non-macro. abs(), fabs() are standard functions, readily understood by reviewers. ABS() is not.

  6. Performance: Profile to find what is best on your platform. What is best (speed, code size, memory size) varies by compiler.

  7. No type checking with ABS().

  8. Cannot take the address of the macro.

like image 88
chux - Reinstate Monica Avatar answered Oct 22 '22 17:10

chux - Reinstate Monica