Search code examples
c++floating-pointstdabsolute-value

Why doesn't std::abs() works with floats


The result of std::abs(0.5f) is 0 because there is no overload for floats. Why? I'm using G++.


Solution

  • You have to be very careful when using the overloads of std::abs as some standard library implementations litter the overloads across many files, some of which get implicitly included into others, like <iostream>.

    If you #include <cmath> or #include <cstdlib> (the second one from C++17) before your std::abs(0.5f) then the float overload will be available. If that's not the case, then there is a bug in your compiler / standard library implementation (unlikely in the case of g++).

    Reference: https://en.cppreference.com/w/cpp/numeric/math/fabs