Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This code prints 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
361 views
Welcome To Ask or Share your Answers For Others

1 Answer

Let's walk through your code:

short a = -5;

a = -5, which fits into a short. So far so easy.

unsigned short b = -5u;

-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)

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 )

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...