Arithmetic operands type casting

Viewed 69

Why in the following code:

short a = 4;
char b = 2;
cout << sizeof(a/b);

sizeof(a/b) is 4? Why is not 2 as size of short?

1 Answers

It is 4 because the type of the expression a / b is int and not short. Excerpt from the The C++ Programming Language book:

Before an arithmetic operation is performed, integral promotion is used to create ints out of shorter integer types.

So, now your (shorter integers) a and b operands are promoted to be of type int. Thus the whole a / b expression becomes int and the size of type int is likely to be 4 bytes on your machine.

The sizeof operator in your case returns the size of the type of the expression which is int, which is 4. The sizeof operator can return:

  • the size of the type
  • the size of the type of an expression

This type conversion is not called type casting but integral promotion.

Related