Search code examples
ctypesintshort

C datatype : Between Short and Int


I read a book talking about C , it's better for me to present the code first and question in the latter.

First Code

#include <stdio.h>

int main(void)
{
short num = 3;

printf("%hd\n" , num );

return 0;

} 


Second Code

#include <stdio.h>

int main(void)
{
short num = 3;

printf("%d\n" , num );

return 0;

}

Special note: I'm using intel based pc so int size is 32-bit.

Question :

1.) The book mention this two code could run correctly although one of it uses the %hd specifier while the other uses %d specifier.

2.)The reason from the book is that because C mechanism would automatically convert the type short to int for faster computation,that is why by using the %d specifier or even %ld which is 32-bit would yield the correct result too.

3.)My question is , when does this conversion occurred??Is it during the time we passed it as an argument to the printf() function , just like how float variable is converted to double when it is passed as an expression or an argument, or by the time we initialize the variable with a value 3??

4.)Actually I've done a small experiment , that is by printing out the size of the variable num using the sizeof operator along with printf() function , and it shows me 2 bytes.But i still not sure when the conversion happen.

5.)If the conversion occurred during the time we assigned the value to the short variable,what's the point of creating a short variable??(**This question should be ignore if it's not the case)

Your help is much appreciated


Solution

  • If you call a function without a prototype or a function with variable arguments, like printf(3), then C applies something called the default argument promotions.

    These conversions promote float to double and anything smaller than int to int or unsigned int. This tends to harmonize most of the types.

    This is an interesting feature that, possibly, C introduced to the world. It actually happens to some extent at the instruction set level or ABI level. Parameters are passed in registers or on the stack, and typically no one allows misaligning the stack or leaving junk in higher-order bits.

    Just one more reason why C matches the hardware so well and runs so fast.