避免编译器遇到的问题abs() [英] Avoiding compiler issues with abs()

查看:224
本文介绍了避免编译器遇到的问题abs()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 std :: abs()函数的 double 变体而不使用 std 与g ++ 4.6.1,没有警告或错误。

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

#include <algorithm>
#include <cmath>

double foobar(double a)
{
     return abs(a);
}

这个版本的g ++似乎是在通过算法中的一个include 将变体 abs() 。这看起来像是标准现在允许的(参见

This version of g++ seems to be pulling in the double variant of abs() into the global namespace through one of the includes from algorithm. This looks like it is now allowed by the standard (see this question), but not required.

如果我使用一个编译器编译上面的代码,并不会拉动 double 变体到 abs()到全局命名空间(如g ++ 4.2),然后报告以下错误:

If I compile the above code using a compiler that does not pull the double variant of abs() into the global namespace (such as g++ 4.2), then the following error is reported:

warning: passing 'double' for argument 1 to 'int abs(int)'

如何强制g ++ 4.6.1和其他编译器将函数拉入全局命名空间,给出警告,以便在使用时可以防止错误其他编译器?

How can I force g++ 4.6.1, and other compilers that pull functions into the global namespace, to give a warning so that I can prevent errors when used with other compilers?

推荐答案

您使用的函数实际上是 abs ,GCC会隐式转换为整数。

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';
}

输出为:


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

-Wconversion 标志为g ++。实际上,当参数是 double 时,该选项的GCC文档明确提到调用 abs 。所有警告选项都可以在此处找到。

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.

这篇关于避免编译器遇到的问题abs()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆