[英]Integer promotion unsigned in c++
int main() {
unsigned i = 5;
int j = -10;
double d = i + j;
long l = i + j;
int k = i + j;
std::cout << d << "\n"; //4.29497e+09
std::cout << l << "\n"; //4294967291
std::cout << k << "\n"; //-5
std::cout << i + j << "\n"; //4294967291
}
I believe signed int
is promoted to unsigned
before doing the arithmetic operators. 我相信在执行算术运算符之前,
signed int
会被提升为unsigned
。
While -10
is converted to unsigned unsigned integer underflow
( is this the correct term?? ) will occur and after addition it prints 4294967291
. 而
-10
将转换为无unsigned integer underflow
无unsigned integer underflow
( 这是正确的术语?? ),并在添加后打印4294967291
。
Why this is not happening in the case of int k
which print -5
? 为什么在打印
-5
的int k
的情况下不会发生这种情况?
The process of doing the arithmetic operator involves a conversion to make the two values have the same type. 执行算术运算符的过程涉及转换以使两个值具有相同的类型。 The name for this process is finding the common type , and for the case of
int
and unsigned int
, the conversions are called usual arithmetic conversions . 此过程的名称是查找公共类型 ,对于
int
和unsigned int
,转换称为常规算术转换 。 The term promotion is not used in this particular case. 在这种特殊情况下不使用促销一词。
In the case of i + j
, the int
is converted to unsigned int
, by adding UINT_MAX + 1
to it. 在
i + j
的情况下,通过UINT_MAX + 1
添加UINT_MAX + 1
,将int
转换为unsigned int
。 So the result of i + j
is UINT_MAX - 4
, which on your system is 4294967291
. 所以
i + j
的结果是UINT_MAX - 4
,在你的系统上是4294967291
。
You then store this value in various data types; 然后,您将此值存储在各种数据类型中; the only output that needs further explanation is
k
. 唯一需要进一步解释的输出是
k
。 The value UINT_MAX - 4
cannot fit in int
. 值
UINT_MAX - 4
不能适合int
。 This is called out-of-range assignment and the resulting value is implementation-defined. 这称为超出范围的赋值 ,结果值是实现定义的。 On your system it apparently assigns the
int
value which has the same representation as the unsigned int
value. 在您的系统它显然分配
int
具有相同的表示作为值unsigned int
的值。
j
will be converted to unsigned int
before addition, and this happens in all your i + j
. j
在添加之前将被转换为unsigned int
,这发生在你所有的i + j
。 A quick experiment. 快速实验。
In the case of int k = i + j
. 在
int k = i + j
的情况下。 As in the case of your implementation and mine, i + j
produces: 4294967291
. 与您的实施和我的实施情况一样,
i + j
产生: 4294967291
。 4294967291
is larger than std::numeric_limits<int>::max()
, the behavior is going to be implementation defined. 4294967291
大于std::numeric_limits<int>::max()
,行为将是实现定义的。 Why not try assigning 4294967291
to an int
? 为什么不尝试将
4294967291
分配给int
?
#include <iostream>
int main(){
int k = 4294967291;
std::cout << k << std::endl;
}
Produces: 生产:
-5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.