Puzzle Type C to Short to Int

I have a question that needs guidance from any expert:

  • Since the value with the type shortis passed as an argument to the function printf(), it is automatically raised to the type int, so the function printf()will see the value as intinstead of the type short.

  • So basically the type shortis 16 bits wide 0000000000000000, and the type intis 32 bits wide , which is equal 00000000000000000000000000000000.

  • Let's say I declare a variable call numwith a type shortand initialize it with a value of -32, which means that the most significant bits of the type shortwill be 1what is 0000000011100000.

  • When I pass this value to printf(), it will be converted to type int, so it will become 00000000000000000000000011100000.

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

  • Why, when I use a specifier %hdor even a specifier %d, will it still ask me for a negative value instead of a positive?

+5
source share
3 answers

No, short and int are signed types, so it is aided by a character extension, not a 0-byte addition:

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

leaving the MSB as 1, i.e. negative.

You can fake the behavior you expect by first entering it unsigned, for example

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

int 16 int. int . ushort.

+2

As you say, it is transformed, and transformation in this case implies knowlegde. This is what the compiler knows as a signed short to int conversion work. It does not just add bits in front, it creates a new int with the same value as short. That is why you get the right number.

+2
source

All Articles