Reputation: 823
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.
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 (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
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
Reputation: 727067
However, I'm wondering why an unsigned int variable of i. e. value
15
shouldn't be promoted to anint
as well. [...] anint
can represent the value15
without any problems
There are two problems with this statement:
int
"; it means "promotion to either an int
or unsigned int
". Therefore, "promoting" an unsigned int
does not make sense: it is already promoted.int
is capable of representing the value 15
is irrelevant, because int
is not capable of representing all values of unsigned int
.Upvotes: 8