Why is the size of the data type different when the value is directly passed to the sizeof operator?
Constants, like variables, have a type of their own:
6.5
: A floating point constant of typedouble
90000
: An integer constant of typeint
(ifint
is 32 bits) orlong
(ifint
is 16 bits)'A'
: A character constant of typeint
in C andchar
in C++
The sizes that are printed are the sizes of the above types.
Also, the result of the sizeof
operator has type size_t
. So when printing the proper format specifier to use is %zu
, not %d
.
Character constants in C (opposite to C++) have the type int
. So this call
printf("%d",sizeof('A'));
outputs 4. That is sizeof( 'A' )
is equal to sizeof( int )
.
From the C Standard (6.4.4.4 Character constants)
10 An integer character constant has type int....
On the other hand (6.5.3.4 The sizeof and alignof operators)
4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.
So the operand of the sizeof
operator in this expression sizeof( 'A' )
has the type int while in this expression sizeof( a )
where a is declared like
char a = 'A';
the operand has the type char
.
Pay attention to that calls like this
printf("%d",sizeof(6.5));
use incorrect conversion format specifier. You have to write
printf("%zu",sizeof(6.5));
Also in the above call there is used a constant of the type double
while in this call
printf("%zu",sizeof(c));
the variable c
has the type float
.
You could get the same result for these calls if the first call used a constant of the type float like
printf("%zu",sizeof(6.5f));