Why is the common type of bool and int8_t an int32_t in C++?

随声附和 提交于 2019-12-23 07:28:37

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/30964431/why-is-the-common-type-of-bool-and-int8-t-an-int32-t-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!