类型何时提升为 unsigned int?

When does a type get promoted to an unsigned int?

这个article说:

If all values of the original type can be represented as an int, the value of the smaller type is converted to an int; otherwise, it is converted to an unsigned int

signed/unsigned charsigned/unsigned short 的所有值都可以表示为 int,那么什么时候类型会提升为 unsigned int

好吧,如果 sizeof(char) == sizeof(int),那么 unsigned char 应该提升为 unsigned int

A short 不能比 int 长,但在某些平台上它可能大小相同。 intlong 也是如此。这意味着如果 "smaller" 是无符号的,那么 "larger" 也必须是无符号的。

这篇文章使用了草率的术语。源类型不必是 "smaller" 而不是 int。这是 C++11 标准所说的:

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

有些平台,例如,unsigned shortint 都是 16 位长。尽管如此,根据定义,unsigned short 的等级 int 并且受到积分提升。在这种情况下,int不能代表所有unsigned short类型的值,所以提升为unsigned int.

编辑:C99 有类似的措辞:

The following may be used in an expression wherever an int or unsigned int may be used:

  • An object or expression with an integer type whose integer conversion rank is less than or equal to the rank of int and unsigned int.
  • A bit-field of type _Bool, int, signed int, or unsigned int.

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. 48) All other types are unchanged by the integer promotions.