Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size of char expression

Tags:

c

sizeof

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

like image 451
Nandyy Avatar asked Sep 01 '14 08:09

Nandyy


2 Answers

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 int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned 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.

like image 164
Yu Hao Avatar answered Oct 11 '22 12:10

Yu Hao


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.

like image 23
M.M Avatar answered Oct 11 '22 12:10

M.M