为什么常见的布尔和int8_t类型是C++中的int32_t

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

本文关键字:C++ 中的 int32 类型 常见 布尔 int8 为什么      更新时间:2023-10-16

我对C++中内置bool类型的一些行为感到好奇。据我了解,std::common_type使用隐式可转换性确定通用类型。我希望带有 bool 和另一种类型的表达式会导致 bool 转换为该类型。例如,我可以看到bool + float -> floatbool + double -> double 。但是,bool + int8_t -> int32_tbool + int16_t -> int32_t .为什么会这样呢?

简短的回答:整体推广

在数值算术中,小积分类型(包括boolcharunsigned charsigned charshortunsigned short等)如果所有可能的值都符合int,则提升为int,否则提升为unsigned int

在当今的大多数机器上,int32_tint 相同。在bool + int8_tbool + int16_t的情况下,两者都被提升为int