C++ int 促进限制的动机

C++ int promotion motivation for restrictions

整数提升的工作原理是将排名较低的所有内容提升到 intuint。但为什么会这样?

区分“升级”和“降级”类型是有意义的。当您将 short 转换为 char 时,您可能会丢失数据。

然而,当排名上升时 (bool -> char -> short -> int -> long -> long long) 没有 丢失数据的机会。如果我有一个 char,无论我将它转换为 short 还是 int,我仍然不会丢失任何数据。

我的问题是为什么只有排名较低的类型才向 int 提升 int?为什么做出这样的决定?为什么不选择下一个排名更高的类型(然后从那里继续,例如再次尝试提升)。

在我看来,当您尝试描述隐式转换语义时,它们似乎有点武断。 “大多数 int 类型都可以“升级”,这意味着转换不会丢失数据,但升级仅适用于 int,而不仅仅是任何更高级别的类型。如果您将任何东西转换为其他东西除了 int,它被称为转换

用int类型的实际排名来尝试一系列的“提升”不是更简单吗?或者只是将任何向更高排名的转换称为“促销”?

P.S。这是一个教育问题,不是一个特定的编程问题,而是出于我自己的好奇心。

C标准中,Section 6.3.1.8 describes "Usual arithmetic conversions."(C99新增,link为C11草案)

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.

C99 Rationale V5.10 将其原因描述为:

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.

根据基本原理,可以合理地推断委员会将此视为捕获最多可能用途的最简单的解决方案。

从简单的角度来看,拥有逐级晋升系统将大大增加实施标准所需的细节。它还会在不同位大小的平台之间产生广泛的性能问题。寻求使用数据类型实现特定目标的程序员仍然可以通过显式类型转换获得这种灵活性。