user4420637
user4420637

Reputation:

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?

Upvotes: 2

Views: 425

Answers (3)

Brian Bi
Brian Bi

Reputation: 119044

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.

Upvotes: 2

Katie
Katie

Reputation: 1270

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.

Upvotes: 2

Severin Pappadeux
Severin Pappadeux

Reputation: 20080

well, if sizeof(char) == sizeof(int), then unsigned char shall be promoted to unsigned int

Upvotes: 0

Related Questions