Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use fabsf rather than fabs

Tags:

c++

I was wondering in what scenario would I use fabs over fabsf (from cmath/math.h)?

Or explain the difference seeing as it looks like one just calls the other.

The definitions I have in my math.h are

_Check_return_ inline float fabs(_In_ float _Xx) _NOEXCEPT

_Check_return_ __inline float __CRTDECL fabsf(_In_ float _X)
like image 889
unknownSPY Avatar asked Oct 17 '22 18:10

unknownSPY


1 Answers

When to use fabsf rather than fabs

In C++, there is hardly ever a reason to use fabsf. Use std::abs instead with floating point types. std::fabs may have use when you wish to convert the absolute value of an integer to double, but that's probably quite niche use case.

If you were writing C instead, then it is almost as simple: Use fabsf when you have a float, and fabs when you have a double. Same applies to other standard math functions with f suffix.

The definitions I have in my math.h are

_Check_return_ inline float fabs(_In_ float _Xx) _NOEXCEPT

The C++ standard library specifies overloads for std::fabs. One of them takes a float. Your standard library is not standard compliant, if the other overloads are missing.

The C standard library specifies double fabs(double). Your standard library is not standard compliant, if the quoted declaration applies to C.

like image 123
eerorika Avatar answered Oct 21 '22 08:10

eerorika