1

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

Gordem
  • 115
  • 9
  • 1
    A [mcve] would be useful. I was unable to reproduce the misbehavior you ran into. – Eljay Aug 14 '20 at 12:31
  • @Eljay It's my mistake, I talked about `abs()`, but wrote `std::abs()`, because I thought that they are the same things. – Gordem Aug 14 '20 at 15:46
  • Ahh, yes, I've made that mistake before. It is one of the reasons I created my *deader files*, which are fake C++ header files that define only the symbols required by the standard and nothing else and do not include any of the other header files. (They compile, but they won't link, and they are effectively non-functional for purposes other than compiling and sanity checking and helping with "include what you use".) – Eljay Aug 14 '20 at 15:51

1 Answers1

7

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

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • And there are two different funcs - `abs` and `std::abs`? And they have different overloads? – Gordem Aug 14 '20 at 09:41
  • 1
    @Gordem: See https://stackoverflow.com/questions/21392627/abs-vs-stdabs-what-does-the-reference-say. It's an absolute mess. I even have a rule for this in my shop: `#include ` and only ever use `std::`. – Bathsheba Aug 14 '20 at 09:43
  • I. e., this mess concerns not only `abs()`? – Gordem Aug 14 '20 at 11:36
  • @Gordem There are other unrelated [messes](https://stackoverflow.com/questions/5004858/why-is-stdmin-failing-when-windows-h-is-included), I'm afraid. – Bob__ Aug 14 '20 at 15:24