c++ - 缩小从 unsigned 到 double 的转换

标签 c++ c++11 warnings double type-conversion

static_assert(sizeof(unsigned) == 4, ":(");
static_assert(sizeof(double) == 8 ,":(");
unsigned u{42};
double x{u};

g++ 4.7.1 提示这段代码:

warning: narrowing conversion of 'u' from 'unsigned int' to 'double' inside { }

为什么这是一个缩小转换?不是每个 unsigned 都可以完美地表示为 double 吗?

最佳答案

Why is this a narrowing conversion?

因为定义包括(我强调):

C++11 8.5.4/7 A narrowing conversion is an implicit conversion [...] from an integer type [...] to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type.

u 不是常量表达式,因此无论源类型的所有可能值是否都可以在目标类型中表示,它都是收缩转换。

Isn't every unsigned perfectly representable as a double?

这是实现定义的。在 32 位 unsigned 和带有 52 位尾数的 double 的常见情况下,就是这种情况;但是一些实现具有更大的 unsigned 和/或更小的 double 表示,因此依赖于该假设的代码不可移植。

关于c++ - 缩小从 unsigned 到 double 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38228357/

相关文章:

c++ - 为什么或为什么不应该使用 'UL' 来指定 unsigned long?

c++ - 从文件中读取字符串格式的信息

c++ - 为接口(interface)和实现设置单独的命名空间是否值得?

c++ - 如何让虚拟析构函数在 C++ 中被调用?

c++11 - 赋值运算符的汇参数实现及语言缺陷

xcode - "cacheParamsComputed"在 Swift 4 中意味着什么?

c++ - 无法在 C++ Visual Studio 中编译 C 文件

c++ - 锁定多个生产者单一消费者

.net - CS1607 : The version specified for the 'file version' is not in the normal 'major.minor.build.revision' format in . 网络

ios - NSURLConnection 在下载大部分数据时导致内存警告