When do I use fabs and when is it sufficient to use std::abs?

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.


There is one more reason to recommend std::fabs for floating-point inputs explicitly.

If you forget to include <cmath>, your std::abs(my_float_num) can be std::abs(int) instead of std::abs(float). It's hard to notice.

Tags:

C++

Math.H

Cmath