Can somebody throw a light on how sizeof(char expression) will be sizeof(int)?
int main()
{
char a, b;
printf("%d\n", sizeof(a+b));
return 0;
}
The program prints 4 as output. I was expecting it to be sizeof(char) i.e., 1
Integer promotion.
When small integral types (smaller than int, such as char, short, etc) are in arithmetic expression, they are automatically promoted to int.
C11 §6.3.1.1 Boolean, characters, and integers
If an
intcan represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to anint; otherwise, it is converted to anunsigned int. These are called the integer promotions. 58)
And in the footnote:
58) The integer promotions are applied only: as part of the usual arithmetic conversions, to certain argument expressions, to the operands of the unary
+,-, and~operators, and to both operands of the shift operators, as specified by their respective subclauses.
a+b is an int expression. a and b would be char expressions.
When using most operators in C, operands of integral type but narrower than int are promoted to int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With