整数提升 - 什么是步骤 [英] Integer promotion - what are the steps
问题描述
此代码打印B2
short a=-5;
unsigned short b=-5u;
if(a==b)
printf("A1");
else
printf("B2");
我读到整数提升,但它仍然不清楚,它在这里的例子是如何工作的?有人可以彻底地发布编译器在加宽/截断值时所遵循的步骤吗?
I read about integer promotion but it's still unclear to me, how does it work in the example here? Can someone thoroughly post the steps the compiler follows in widening/truncating the values?
推荐答案
>
Let's walk through your code:
short a = -5;
a = -5,到目前为止很容易。
a = -5, which fits into a short. So far so easy.
unsigned short b = -5u;
-5u表示应用一元 -
到常数5u。 5u是(unsigned int)5,并且一元 -
没有促销,所以你最终得到4294967291这是2 ^ 32-5。 (更新:我的原始答案有点错误;看到一个测试脚本显示此版本是正确的在这里 http://codepad.org/hjooaQFW )
-5u means apply the unary -
operator to the constant 5u. 5u is (unsigned int) 5, and the unary -
does no promotion, so you end up with 4294967291 which is 2^32-5. (Update: I got this bit wrong in my original answer; see a test script which shows this version is correct here http://codepad.org/hjooaQFW)
现在当把它放在b中时,它被截断为一个无符号short(通常为2个字节),所以b = 65531,即2 ^ 16 -5。
Now when putting that in b, it is truncated to an unsigned short (2 bytes, usually), so b = 65531, which is 2^16-5.
if( a == b )
在这一行中,a和b都被提升为int,以便比较可以正确进行。如果他们被晋升为短裤,b可能缠绕。如果他们被提升为未签名的短裤,一个可能的环绕。
In this line, a and b are both promoted to ints so that the comparison can happen correctly. If they were promoted to shorts, b would potentially wrap around. If they were promoted to unsigned shorts, a would potentially wrap around.
这就像说 if((int)a == b)
。和a = -5,所以(int)a = -5,b = 65531,所以(int)b = 65531,因为int比shorts大。
So it's like saying if( (int) a == (int) b )
. And a = -5, so (int) a = -5, and b = 65531, so (int) b = 65531, because ints are bigger than shorts.
这篇关于整数提升 - 什么是步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!