August Karlstrom August Karlstrom - 1 year ago 75
C Question

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download