Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic operands type casting

Tags:

c++

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?

like image 389
michalt38 Avatar asked Jan 25 '23 05:01

michalt38


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.

like image 175
Ron Avatar answered Feb 01 '23 17:02

Ron