简体   繁体   中英

Puzzle by C type promotion from short to int

I have a question that needs guidance from any expert:

  1. As a value with short type is passed as an argument to printf() function, it'll be automatically promoted to int type, that is why the printf() function will see the value as int type instead of short type.

  2. So basically short type is 16-bits wide, which is 0000000000000000 while int type is 32-bits wide, which is 00000000000000000000000000000000 .

  3. Let's say I declare a variable call num with short type and initialise it with a value of -32, that means the most significant bits of the short type will be 1 , which is 0000000011100000 .

  4. When I pass this value to printf() , it'll be converted to int type, so it'll become 00000000000000000000000011100000 .

  5. In step 4, when it is converted to int , the most significant bit is 0 .

  6. Why, when I use the %hd specifier or even the %d specifier, will it still still prompt me for a negative value instead of a positive?

No, short and int are both signed types, so it is promoted by sign extension not 0-byte padding:

-32 short =                   11111111 11100000 
-32 int   = 11111111 11111111 11111111 11100000

leaving the MSB as 1 ie negative.

You could fake the behavour you're expecting by casting it unsigned first, eg

printf("%d", (unsigned short)((short)(-32)));

Converting a short to an int basically replicates the most significate bit of the short into the top 16 bits of the int. This is why the int is printed as negative. If you do not want this behaviour using a ushort .

As you say it is converted and conversion in this case implies knowlegde. That is the compiler knows how signed short to int conversion work. It does not just append bits in front, it creates a new int with the same value as the short. That's why you get the correct number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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