I assume that abs
and fabs
are behaving different when using math.h
. But when I use just cmath
and std::abs
, do I have to use std::fabs
or fabs
? Or isn't this defined?
Basically, both is used to get the absolute value of the given value. abs() is used for Integer values whereas fabs() is used for floating type data.
The fabs() function in C++ returns the absolute value of the argument. It is defined in the cmath header file.
In C++, it's always sufficient to use std::abs
; it's overloaded for all the numerical types.
In C, abs
only works on integers, and you need fabs
for floating point values. These are available in C++ (along with all of the C library), but there's no need to use them.
It's still okay to use fabs
for double
and float
arguments. I prefer this because it ensures that if I accidentally strip the std::
off the abs
, that the behavior remains the same for floating point inputs.
I just spent 10 minutes debugging this very problem, due to my own mistake of using abs
instead of std::abs
. I assumed that the using namespace std;
would infer std::abs
but it did not, and instead was using the C version.
Anyway, I believe it's good to use fabs
instead of abs
for floating-point inputs as a way of documenting your intention clearly.
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