Search code examples
cintegerinteger-promotion

Is it expected for sizeof(char) to return 1 instead of 4 when integer promotion takes place in C?


#include <stdio.h>

int main()
{
   unsigned char c = 'a';
    c = c + 3;
    printf("%c ", c);
    printf("%zu",sizeof(c));

    return 0;
}

Output:d 1

when integer promotion takes place implicitly in c. then why the size of char is printing 1(in bytes) rather 4(in bytes), since the size should increase to 32bits right?

Iam thinking that the output shall be: d 4


Solution

  • It's correct that the calculation of c + 3 involves integer promotion, i.e. the type of the result is int. However, when you store that result in your charvariable using c = ... it will be converted back to a char again. The assignment will not (can not) change the size of your variable.

    Try this code:

    char c = 'a';
    printf("%zu\n", sizeof(c));
    printf("%zu\n", sizeof(c + 3));
    c = c + 3;
    printf("%zu\n", sizeof(c));
    

    On my system it gives:

    1
    4
    1