简体   繁体   中英

When does a type get promoted to an unsigned int?

This article says:

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

All values of signed/unsigned char and signed/unsigned short can be represented as an int , so when does a type gets promoted to an unsigned int ?

A short cannot be longer than an int but on some platforms it may be the same size. The same goes for int and long . This means that if the "smaller" one is unsigned, the "larger" one must be too.

The article is using sloppy terminology. The source type doesn't have to be "smaller" than int . Here is what the C++11 standard says:

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 .

There are platforms on which, say, unsigned short and int are both 16 bits long. Nevertheless, unsigned short has lower rank than int by definition and is subject to integral promotion. In this case, int cannot represent all values of type unsigned short , so the promotion is to unsigned int .

Edit: C99 has similar wording:

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.

好吧,如果sizeof(char)== sizeof(int),则将unsigned char提升为unsigned int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM