#include <cstdint>
#include <iostream>
int main() {
uint32_t i = -64;
int32_t j = i;
std::cout << j;
return 0;
}
我尝试过的大多数编译器都会创建输出 -64
的程序,但这是定义的行为吗?
- 将有符号整数分配给无符号整数
uint32_t i = -64;
是否定义了行为? - 有符号整数赋值
int32_t j = i;
,当i
等于4294967232
时,定义了行为吗?
最佳答案
对于无符号整数越界转换,定义结果;对于有符号整数,它是实现定义的。
C++11(ISO/IEC 14882:2011) §4.7 Integral conversions [conv.integral/2]
If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]
If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.
此文本在 C++14 中保持不变。
关于c++ - 有符号到无符号转换,并返回,整数的定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18994563/