Multisync
Multisync

Reputation: 823

Why are unsigned integer variables generally not affected by integer promotions?

After reading quite a couple of questions on integer promotions, it seems to be the common understanding that integer promotions or only applied to small integer types, such as short int or char.

However, I'm wondering why an unsigned int variable of i. e. value 15 shouldn't be promoted to an int as well. After all, it's conversion rank is equal to the rank of int and unsigned int, as requested by statement (1) in the citation below.

As an int can represent the value 15 without any problems (on all plattforms I know of), it should get converted to an int.

Integer promotions

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

  1. 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.

  2. A bit-field of type _Bool, int, signed int, or unsigned int.

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.

Upvotes: 2

Views: 188

Answers (2)

Oleksii Shmalko
Oleksii Shmalko

Reputation: 3778

Usually, it's impossible to say at compile-time what values will variables hold when promotion will actually occur.

Investigating value of variable to choose appropriate type at runtime introduces too much overhead, as well as simply impossible. So, only things compiler has are types.

I think main reason to prefer unsigned types over signed is that unsigned integer overflow is defined, while overflow of signed integer is undefined behavior.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

However, I'm wondering why an unsigned int variable of i. e. value 15 shouldn't be promoted to an int as well. [...] an int can represent the value 15 without any problems

There are two problems with this statement:

  • Integer promotions does not mean "promotion to an int"; it means "promotion to either an int or unsigned int". Therefore, "promoting" an unsigned int does not make sense: it is already promoted.
  • Integer promotion rules do not take into consideration the current value of an expression. The rules are specifically written in a way to talk about all values of a type. Hence, the fact that an int is capable of representing the value 15 is irrelevant, because int is not capable of representing all values of unsigned int.

Upvotes: 8

Related Questions