Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puzzle by C type promotion from short to int

Tags:

c

types

int

short

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?

like image 503
caramel1995 Avatar asked May 09 '11 09:05

caramel1995


3 Answers

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)));
like image 148
Rup Avatar answered Oct 20 '22 06:10

Rup


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.

like image 35
Richard Schneider Avatar answered Oct 20 '22 05:10

Richard Schneider


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.

like image 45
RedX Avatar answered Oct 20 '22 06:10

RedX