【问题标题】:g++ -Wall not warning about double-> int castg++ -Wall 没有关于 double-> int cast 的警告
【发布时间】:2011-04-05 14:01:47
【问题描述】:

在下面的 sn-p 中不会产生任何警告。 g++4.4.3 -Wall -pedantic

//f is
void f(int );

f(3.14);
double d = 3.14;
int i = d+2;

我强烈记得这是一个警告,类似于“可能丢失精度”。是被删除了还是我的记忆在欺骗我?

如何在 g++ 中将其变成警告?我觉得这是一个有用的警告,还是一个坏主意?

我什至在http://gcc.gnu.org/onlinedocs/gcc-4.4.5/gcc/Warning-Options.html 找不到合适的东西

【问题讨论】:

    标签: c++ g++


    【解决方案1】:
    $ gcc -Wconversion test.c
    
    test.c: In function ‘main’:
    test.c:3: warning: conversion to ‘int’ from ‘double’ may alter its value
    

    【讨论】:

    • 是的,这可以解决问题。我觉得很奇怪它没有包含在 -Wall 中。
    • 它会导致数百个与整数相关的转换警告,这就是为什么在-Wall 中未启用它的原因。也许使用gcc.gnu.org/bugzilla/show_bug.cgi?id=53001 会更简单。
    【解决方案2】:

    使用-Wconversion 选项。 -Wall 不包括它。

    使用-Wconversion 选项,GCC 会给出以下警告消息:

    警告:转换为 'int' 会改变 'double' 常量值
    警告:从 'double' 转换为 'int' 可能会改变其值

    【讨论】:

      【解决方案3】:

      除了其他答案提到的之外,还值得一提的是,在 C++0x 中 {} 初始化并没有缩小。因此,例如,您不会收到警告,而是会收到错误

      void f(int x)
      {
         // code
      }
      
      int main()
      {
         f({3.14}); // narrowing conversion of '3.14000000000000012434497875801753252744674682617e+0' from 'double' to 'int' inside { }
      }
      

      g++ 4.4 及以上支持初始化列表(带有-std=c++0x 选项)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-31
        • 2021-12-31
        • 1970-01-01
        • 2016-05-15
        相关资源
        最近更新 更多