I tried to add bool value together, say:
bool i = 0, j = 0, k = 0;
cout << sizeof(i + j + k) << endl;
The result is 4, which means, the result is converted to a 'int' value.
I want to ask: Is this a C/C++ standard operation? does the compiler always guarantee that the temporary value to be converted to a larger type if it overflows? Thanks!
Thanks for the answers, one follow up question:
say, if I do:
unsigned short i = 65535, j = 65535;
cout << sizeof(i + j) << endl;
The result is 4. Why it's been promoted to 'int'?
It's not the overflow that causes the conversion, it's the very fact you did arithmetic at all. In C++ (and C where the behaviour originated), the operands of basic arithmetic operators on built-in types go through a set of well-defined promotions before the calculation is made. The most of basic of these rules (somewhat simplified) is that any type smaller than an int
gets promoted to int
.
Your followup question has the same answer - your short
is smaller than an int
, so it gets promoted to an int
before the addition takes place.
This StackOverflow question has several answers that describe the promotions in more detail.
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