C++ int promotion motivation for restrictions

Viewed 328

Integer promotion works by promoting everything of an inferior rank to either int or uint. But why is this so?

It makes sense to make a difference between "upgrading" and "downgrading" a type. When you are converting a short to a char you may lose data.

However when going up in ranks (bool -> char -> short -> int -> long -> long long) there is no chance to lose data. If I have a char it doesnt matter if I convert it to a short or an int, I still won't lose any data.

My question is why is int promotion only from a lower ranked type towards int? Why was the decision made to have it like this? Why not towards the next higher ranked type for example (and the go on from there, try to promote again for example).

Seems to me that the implicit conversion semantics seem a bit arbitrary when you try to describe them. "most int types can be "promoted", meaning a conversion with no possibility of data loss, but the promotion only works towards int, not just any higher ranked type. If you convert anything to something else other than int it is called a conversion"

Would it not be simpler to use the actual ranks of the int types to attempt a series of "promotions"? Or just to call any conversion towards a higher ranked int a "promotion"?

P.S. this is an educational question not one a bout a specific programming issue but rather for my own curiosity.

1 Answers

In the C standard, Section 6.3.1.8 describes "Usual arithmetic conversions." (Added in C99, link is to C11 draft)

Many operators that expect operands of arithmetic type cause conversions and yield result types in a similar way. The purpose is to determine a common real type for the operands and result.

The C99 Rationale V5.10 describes the reason for this as:

Explicit license was added to perform calculations in a “wider” type than absolutely necessary, since this can sometimes produce smaller and faster code, not to mention the correct answer more often. Calculations can also be performed in a “narrower” type by the as if rule so long as the same end result is obtained. Explicit casting can always be used to obtain a value in a desired type.

From the rationale, it is reasonable to infer the committee sees this as the simplest solutions that captures the greatest number of possible uses.

From a simplicity standpoint, having a rank-by-rank promotion system would greatly increase the detail required to implement the standard. It would also create a wide variation of performance issues between platforms of different bit sizes. Programmers seeking to achieve specific objectives with data types are still given that flexibility through explicit casting of types.

Related