I'm curious about some of the behavior of the builtin bool
type in C++. As I understand it, std::common_type
determines the common type using implicit convertibility. I would expect that an expression with bool
and another type would cause bool to convert to that type. For instance, I can see that bool + float
-> float
and bool + double
-> double
. However, bool + int8_t
-> int32_t
and bool + int16_t
-> int32_t
. Why is this the case?
Asked
Active
Viewed 1,280 times
10

Yu Hao
- 119,891
- 44
- 235
- 294

user2333829
- 1,301
- 1
- 15
- 25
1 Answers
10
Short answer: integral promotion.
In numerical arithmetic, small integral types (including bool
, char
, unsigned char
, signed char
, short
, unsigned short
, etc) are promoted to int
if all the possible values fit in int
, otherwise they are promoted to unsigned int
.
On most machines today, int32_t
is the same as int
. In the case of bool + int8_t
or bool + int16_t
, both are promoted to int
.

Yu Hao
- 119,891
- 44
- 235
- 294
-
Thanks Yu Hao! That's great. Do you know where this is mentioned in the standard? – user2333829 Jun 21 '15 at 12:42
-
1@user2333829 *§4.5 Integral promotions* – Yu Hao Jun 21 '15 at 12:51
-
Thanks, you answered my question! I find that weird, but it's clearly there. – user2333829 Jun 21 '15 at 12:55
-
3@user2333829 [Why must a short be converted to an int before arithmetic operations in C and C++?](http://stackoverflow.com/q/24371868/995714) – phuclv Jun 21 '15 at 14:11