I have a question that needs guidance from any expert:
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.
So basically short
type is 16-bits wide, which is 0000000000000000
while int
type is 32-bits wide, which is 00000000000000000000000000000000
.
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
.
When I pass this value to printf()
, it'll be converted to int
type, so it'll become 00000000000000000000000011100000
.
In step 4, when it is converted to int
, the most significant bit is 0
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With