是否签名为无符号转换,然后返回定义的整数行为? [英] Is signed to unsigned conversion, and back, defined behaviour for integers?
问题描述
#include <cstdint>
#include <iostream>
int main() {
uint32_t i = -64;
int32_t j = i;
std::cout << j;
return 0;
}
我尝试过的大多数编译器都会创建输出 -64
,但这是定义的行为吗?
Most compilers I've tried will create programs that output -64
, but is this defined behaviour?
- 是否将有符号整数赋值给无符号整数
uint32_t i = -64;
已定义的行为? - 有符号整数赋值
int32_t j = i;
,当i
等于4294967232
,定义的行为?
- Is the assignment of a signed integer to and unsigned integer
uint32_t i = -64;
defined behaviour? - Is the signed integer assignment
int32_t j = i;
, wheni
equals4294967232
, defined behaviour?
推荐答案
对于无符号整数超范围转换,定义结果;对于有符号整数,它是实现定义的。
For unsigned integer out-of-range conversion, the result is defined; for signed integers, it's implementation-defined.
C ++ 11(ISO / IEC 14882:2011)§4.7完整转换[转换。 integer / 2]
如果目标类型是无符号的,则结果值是与源整数一致的最小无符号整数(模2 ^ n,其中n是数字用于表示无符号类型的位)。 [注意:在二进制补码表示中,此转换是概念性的,并且位模式没有变化(如果没有截断)。 -end note]
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,此文本保持不变。
This text remains the same for C++14.
这篇关于是否签名为无符号转换,然后返回定义的整数行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!