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

97 Views Asked by At
#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

2

There are 2 best solutions below

1
Support Ukraine On BEST ANSWER

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
4
t0mm13b On

Please see the C99 Standard or C11 Standard, under section 6.5.3.4 titled 'The sizeof and _Alignof operators' - Point #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

For the C99 standard, under section 6.5.3.4 titled The sizeof operator Point #3 -

When applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.

Meaning, no matter what implementation of compiler used or environment, the size of char, the result will always be 1.

There is a quoted sample of code under Section 5.1.2.3 of the C99 standard, reference #10

EXAMPLE 2 In executing the fragment

char c1, c2; 
/* ... */ 
c1 = c1 + c2;

the ‘‘integer promotions’’ require that the abstract machine promote the value of each variable to int size and then add the two ints and truncate the sum. Provided the addition of two chars can be done without overflow, or with overflow wrapping silently to produce the correct result, the actual execution need only produce the same result, possibly omitting the promotions.

So, on the basis of the question, yes, the integer promotion will happen, it is after re-evaluating back to type of char will always return back 1 afterwards. As long as there's no over-flow of the value and that it falls under the maximum size of byte value, i.e. 255.