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?
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:
This type conversion is not called type casting but integral promotion.
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