整型提升 - 哪些步骤 [英] Integer promotion - what are the steps

查看:146
本文介绍了整型提升 - 哪些步骤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这code打印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?

推荐答案

让我们通过您的code:

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是(无符号整数)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时,被截断的无符号短(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都被提升到整数,使得比较可以正确地发生。如果他们被提拔到短路,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)一==(INT)B)。且a = -5,所以(int)的一个= -5,以及b = 65531,所以(int)的B = 65531,因为整数比短裤更大

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆