c++ - 将 double 降级为 float 时没有警告

标签 c++ macos g++ double

<分区>

当我在装有 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.

关于c++ - 将 double 降级为 float 时没有警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26091955/

相关文章:

c++ - C++ 编译器隐式实例化模板类的所有成员函数是否有效?

c++ - 等于在 C++ 中返回 false

c++ - g++编译错误信息:/usr/bin/ld: cannot find -lssl

c++ - AUHAL 单元的 AudioBufferList,其输出流格式被压缩。

Python:pip 尝试安装到/bin 目录

macos - 如何创建要保存到新文档的文档范围书签?

c++ - std::async 将创建和异步执行的最大线程数是多少?

c++ - 错误 : not all control paths return a value

C++ |为什么执行这个程序后我会得到奇怪的字符?

c++ - 为什么 enable_if 不能在这里工作?