Avoiding compiler issues with abs()

后端 未结 2 402
独厮守ぢ
独厮守ぢ 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: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 
    #include 
    
    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.

提交回复
热议问题