This question already has answers here:
Signed to unsigned conversion in C - is it always safe?
(8个答案)
7年前关闭。
执行此操作给我4294967260
我知道正在发生从有符号的int到无符号的int的转换,
但是如何以及为什么这个特殊的值(value)?
我注意到它接近|的总和。 2147483647 | + 2147483647
(8个答案)
7年前关闭。
#include <iostream>
int main ()
{
using namespace std;
unsigned int i = 4;
int a = -40;
cout<<a+i<<endl;
return 0;
}
执行此操作给我4294967260
我知道正在发生从有符号的int到无符号的int的转换,
但是如何以及为什么这个特殊的值(value)?
我注意到它接近|的总和。 2147483647 | + 2147483647
最佳答案
当unsigned int
和int
一起添加时,在添加之前int
首先转换为unsigned int
(结果也是unsigned int
)。
-1虽然是第一个负数,但实际上它等于最大的无符号数,即(unsigned int) -1 === UINT_MAX
。
无符号形式的-2是UINT_MAX - 1
,依此类推,所以是-40 === UINT_MAX - 39 === 4294967256
(使用32位int时)。
当然,加4即可得出答案:4294967256 + 4 = 4294967260
。
这是一个很棒的测验,您可以在其中学习C(和类似的C++)中的一些整数规则:http://blog.regehr.org/archives/721