【问题标题】:GCC -Wconversion warns in conjunction with negation, but not otherwiseGCC -Wconversion 与否定一起发出警告,但不是其他情况
【发布时间】:2015-06-03 04:47:59
【问题描述】:

获取这段代码:

int main()
{
  short a = 2, b = 1;
  float f = 5.36f;

  -a * f;
  b * f;
}

编译:

~ $ g++ -std=c++11 wconversion.cpp -Wconversion
wconversion.cpp: In function ‘int main()’:
wconversion.cpp:6:8: warning: conversion to ‘float’ from ‘int’ may alter its value [-Wconversion]
   -a * f;

为什么它会警告a,而不是b

编辑:因为它似乎取决于编译器版本:我使用的是 GCC 4.9。此外,在 ab 不是常量的其他代码中,该行为也是相同的。

【问题讨论】:

    标签: c++ gcc floating-point gcc-warning


    【解决方案1】:

    这取决于 gcc 的版本。在 4.4.5 中,我在两行都收到警告:

    foo.c:2: warning: function declaration isn’t a prototype
    foo.c: In function ‘main’:
    foo.c:6: warning: conversion to ‘float’ from ‘int’ may alter its value
    foo.c:6: warning: statement with no effect
    foo.c:7: warning: conversion to ‘float’ from ‘int’ may alter its value
    foo.c:7: warning: statement with no effect
    foo.c:8: warning: control reaches end of non-void function
    

    也许开发人员做了一个特殊情况,认识到b 是“1”并且存在精确转换,而“-2”在用户方面会遇到潜在的歧义(除了特殊情况,转换将四舍五入 - 启发式可能需要改进)。使用 gcc 4.9,我只收到一个警告:

    foo.c:1:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes]
     int main()
     ^
    foo.c: In function ‘main’:
    foo.c:6:6: warning: conversion to ‘float’ from ‘int’ may alter its value [-Wconversion]
       -a * f;
          ^
    foo.c:6:3: warning: statement with no effect [-Wunused-value]
       -a * f;
       ^
    foo.c:7:3: warning: statement with no effect [-Wunused-value]
       b * f;
       ^
    foo.c:8:1: warning: control reaches end of non-void function [-Wreturn-type]
     }
     ^
    gcc (Debian 4.9.2-10) 4.9.2
    

    【讨论】:

    • 更新了我的问题,我使用的是 4.9,对于 ab 不恒定的代码,警告是相同的。
    【解决方案2】:

    警告是什么意思?

    32 位类型int 的某些值不能完全表示为float。如果将这样的int 值转换为float,将选择最接近的float(两个周围的浮点数之间的选择是实现定义的,但几乎所有实现都会选择最近的一个)。

    警告似乎是关于从int 或更宽的整数类型转换为float 期间的信息丢失。

    智能编译器是否应该针对b 发出警告?

    智能编译器不需要为b 发出警告,因为bshort(在OP 的架构上可能是16 位),并且b 的所有值在运行时都可能具有-time 可以完全表示为float

    智能编译器是否应该针对-a 发出警告?

    出于同样的原因,智能编译器可以避免a 的警告。 -a 的类型为 int 因为促销,但 -a 的值范围从 -(215-1) 到 215(在 OP 的平台上)。所有这些值都可以精确地表示为浮点数。但是,这里似乎触发的一般警告是针对int 或更宽类型的表达式。 GCC 似乎无法检测到消息警告的情况不会出现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多