简体   繁体   English

签到未签名的演员

[英]signed to unsigned casting

look at this code: 看看这段代码:

void main ()
{
int i = -1;
unsigned u = 1;

cout << u + i;
}

the addition of the u (unsigned) and i (signed), so i must be converted to the unsigned type, so it should be interpreted ( (2 ^ 32) - 1 ) and the expression should change from: -1 + 1 to ( (2 ^ 32) - 1 ) + 1 but when i run the code it results to 0 why? 添加u(无符号)和i(有符号),所以我必须转换为无符号类型,因此它应该被解释((2 ^ 32) - 1)并且表达式应该从:-1 + 1变为((2 ^ 32) - 1)+ 1但是当我运行代码时,结果为0为什么?

-1 in an unsigned representation of the largest possible number unsigned can hold ( UINT_MAX ). -1表示无符号最大可能数的无符号表示可以保持( UINT_MAX )。

Adding 1 to this wraps over due to the properties of unsigned , thus equaling 0. 由于unsigned的属性,因此将0添加到此包装,因此等于0。

(unsigned) -1 is 0xFFFFFFFF. (无符号)-1是0xFFFFFFFF。 1 + 0xFFFFFFFF = 0x100000000 which overflows the int, and results in 0. 1 + 0xFFFFFFFF = 0x100000000溢出int,结果为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM