开发者

Puzzle by C type promotion from short to int

I have a question that needs guidance from any 开发者_Python百科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 i.e. negative.

You could fake the behavour you're expecting by casting it unsigned first, e.g.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜