[英]Is it portable to cast the max value of a unsigned int into an int and exepect the result to be -1?
I've found a C++ code where we cast an unsigned int 32, initialized to its max value, into a signed int and expect it to be -1
.我找到了一个 C++ 代码,我们将一个初始化为最大值的 unsigned int 32 转换为一个有符号 int 并期望它是
-1
。 It works well on the tested compiler, but is it really portable?它在经过测试的编译器上运行良好,但它真的可移植吗?
int GetBusinessDataID()
{
u32_t id = ~0;
// Some code that may return a valid ID.
return id; // Here we expect to return -1.
}
This is guaranteed for integral conversions since C++20;从 C++20 开始,这对于整数转换是有保证的; before C++20 this is implementation-defined.
在 C++20 之前,这是实现定义的。
If the destination type is signed, the value does not change if the source integer can be represented in the destination type.
如果目标类型是有符号的,并且源整数可以在目标类型中表示,则该值不会更改。 Otherwise the result is
否则结果是
implementation-defined (until C++20)
实现定义(直到 C++20)
the unique value of the destination type equal to the source value modulo 2 n where n is the number of bits used to represent the destination type.
目标类型的唯一值等于源值模 2 n ,其中n是用于表示目标类型的位数。 (since C++20).
(从 C++20 开始)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.