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))
Code should use abs()
with int
(or narrower), fabs()
with double, fabsf()
with float
, labs(x)
with long
, etc. @Joachim Pileborg
Advantage: non-macro. Macro ABS()
evaluates the argument twice, likely not desired as in ABS(x++)
. @EOF and @EOF
Advantage: non-macro. Sequence point definitiveness. @EOF
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.
Advantage: non-macro. ABS(0.0/0.0)
attempts to change the sign. (Corner case concern).
Advantage: non-macro. abs()
, fabs()
are standard functions, readily understood by reviewers. ABS()
is not.
Performance: Profile to find what is best on your platform. What is best (speed, code size, memory size) varies by compiler.
No type checking with ABS()
.
Cannot take the address of the macro.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With