The whole promotion - what are the steps

This code prints B2

short a=-5; unsigned short b=-5u; if(a==b) printf("A1"); else printf("B2"); 

I read about whole ads, but itโ€™s still unclear to me how this works in the example here? Can someone fully publish the steps that the compiler should follow when expanding / truncating values?

+7
source share
3 answers

Skip your code:

 short a = -5; 

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

 unsigned short b = -5u; 

-5u means apply the unary operator to the 5u constant. 5u is (unsigned int) 5, and unary does not advance, so you get 4294967291, which is 2 ^ 32-5. (Update: I was wrong in my original answer, see Test script, which shows that this version is correct here http://codepad.org/hjooaQFW )

Now that it fits in b, it is truncated with an unsigned short (usually 2 bytes), so b = 65531, which is 2 ^ 16-5.

 if( a == b ) 

On this line, a and b both rise to ints, so the comparison can happen correctly. If they were promoted to shorts, b would potentially turn around. If they were translated into unsigned shorts, a would potentially wrap around.

So how to say if( (int) a == (int) b ) . And a = -5, therefore (int) a = -5 and b = 65531, therefore (int) b = 65531, because ints are more shorts.

+8
source
 a == b 

a and b both upgraded to int in the above expression.

 unsigned short b=-5u; 

In this declaration, -5U converted to unsigned short by an integer conversion (C99, 6.3.1.3p2 applies here) and becomes a large value.

(C99, 6.3.1.3p2) "Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting more than the maximum value that can be represented in the new type until the value is in the range of the new type."

b value then (unsigned short) ((unsigned int) USHRT_MAX + 1 -5) , which is (unsigned short) 65531 if USHRT_MAX is equal to (unsigned short) 65535 .

So you have:

(short) -5 == (unsigned short) 65531

which is equivalent after the integral advancement of both operands to:

-5 == 65531

which is equivalent to 0 .

+3
source

short to unsigned short is a conversion (it has a conversion rank)

short - int is a promotion (with a promotion rating)

Stocks are preferred over transitions due to ranking. Promotions are held during arithmetic and other operations. Conversions occur when you simply store one integral type inside another. Arithmetic operations can cause conversions as well as promotions to combine types. For another example:

 unsigned int u = 2; int i = 2; u + i; 

i converts (does not advance) to unsigned .

Your value is converted to a larger value because it is wrapped due to unsigned . Then they are promoted to int . So a != b because of this.

0
source

All Articles