Avoiding compiler issues with abs()

后端 未结 2 388
独厮守ぢ
独厮守ぢ 2020-12-15 09:06

When using the double variant of the std::abs() function without the std with g++ 4.6.1, no warning or error is given.



        
相关标签:
2条回答
  • 2020-12-15 09:14

    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) 
    
    0 讨论(0)
  • 2020-12-15 09:32

    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.

    0 讨论(0)
提交回复
热议问题