当我在装有 OSX 10.8 和 g++ 4.2.1 的 Mac 64 位机器上编译以下代码时,没有生成警告。
#include "stdio.h"
int main()
{
double d= 3.14159;
float res= d;
printf("%f\n", res);
return 0;
}
显然,自动将 double 降级为 float 可能非常危险,但编译器不会生成任何警告。我能找到的唯一解决方案是使用标志 -Wshorten-64-to-32。
在我看来,这是一个如此明显的错误,令我惊讶的是编译器默认情况下并未捕获此错误。默认情况下 g++ 不捕获此错误有什么原因吗?有没有更好的方法在不使用 -Wshorten-64-to-32 的情况下生成警告?
如果您想知道,-Wall 也不会生成警告...
提前感谢您的帮助。
行为符合标准:
4.8 Floating point conversions [conv.double]
A prvalue of floating point type can be converted to a prvalue of another floating point type. If the
source value can be exactly represented in the destination type, the result of the conversion is that exact
representation. If the source value is between two adjacent destination values, the result of the conversion
is an implementation-defined choice of either of those values. Otherwise, the behavior is undefined.
此外,浮点型值可以转换为整型值:
4.9 Floating-integral conversions [conv.fpint]
A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates;
that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be
represented in the destination type.