Avoiding compiler issues with abs()

The function you are using is actually the integer version of abs, and GCC does an implicit conversion to integer.

This can be verified by a simple test program:

#include <iostream>
#include <cmath>

int main()
{
    double a = -5.4321;
    double b = std::abs(a);
    double c = abs(a);

    std::cout << "a = " << a << ", b = " << b << ", c = " << c << '\n';
}

Output is:

a = -5.4321, b = 5.4321, c = 5

To get a warning about this, use the -Wconversion flag to g++. Actually, the GCC documentation for that option explicitly mentions calling abs when the argument is a double. All warning options can be found here.


Be warned, you don't need to explicitly #include <cmath>, <iostream> does the damage as well (and maybe some other headers). Also, note that -Wall doesn't give you any warnings about it.

#include <iostream>

int main() {
  std::cout << abs(.5) << std::endl;
  std::cout << typeid(decltype(abs)).name() << std::endl;
}

Gives output

0
FiiE

On

gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04) 

Tags:

C++