Puzzle by C type promotion from short to int
I have a question that needs guidance from any 开发者_Python百科expert:
As a value with
short
type is passed as an argument toprintf()
function, it'll be automatically promoted toint
type, that is why theprintf()
function will see the value asint
type instead ofshort
type.So basically
short
type is 16-bits wide, which is0000000000000000
whileint
type is 32-bits wide, which is00000000000000000000000000000000
.Let's say I declare a variable call
num
withshort
type and initialise it with a value of -32, that means the most significant bits of theshort
type will be1
, which is0000000011100000
.When I pass this value to
printf()
, it'll be converted toint
type, so it'll become00000000000000000000000011100000
.In step 4, when it is converted to
int
, the most significant bit is0
.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.
精彩评论