cintegercharconstantssizeof

Why is the size of the data type different when the value is directly passed to the sizeof operator?


#include <stdio.h>
int main() {
    char a = 'A';
    int b = 90000;
    float c = 6.5;
    printf("%d ",sizeof(6.5));
    printf("%d ",sizeof(90000));
    printf("%d ",sizeof('A'));
    printf("%d ",sizeof(c));
    printf("%d ",sizeof(b));
    printf("%d",sizeof(a));
    return 0;
}

The output is:

8 4 4 4 4 1

Why is the output different for the same values?


Solution

  • 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));