c++ - 为什么在 C 和 C++ 中算术运算之前必须将 Short 转换为 int?

标签 c++ c int short integer-promotion

根据我从 this question 得到的答案看来,C++ 继承了在从 C 执行算术运算时将 short 转换为 int 的要求。我可以请您思考一下为什么 这首先是在 C 中引入的?为什么不直接将这些操作作为short进行呢?

例如(取自评论中 dyp 的建议):

short s = 1, t = 2 ;
auto  x = s + t ;

x 的类型为 int

最佳答案

如果我们看一下Rationale for International Standard—Programming Languages—C6.3.1.8部分通常的算术转换它说(强调我的前进):

The rules in the Standard for these conversions are slight modifications of those in K&R: the modifications accommodate the added types and the value preserving rules. 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

Section 6.3.1.8来自draft C99 standard涵盖应用于算术表达式操作数的常用算术转换,例如 6.5.6 Additive operators 部分说:

If both operands have arithmetic type, the usual arithmetic conversions are performed on them.

我们在 6.5.5 Multiplicative operators 部分找到类似的文本以及。对于操作数,首先从6.3.1.1 Boolean, characters, and integers部分应用整数提升其中说:

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.

基本原理或国际标准 - 编程语言 - C6.3.1.1 部分关于整数提升的讨论实际上更有趣,我将选择性地引用 b/c 因为它太长而无法完整引用:

Implementations fell into two major camps which may be characterized as unsigned preserving and value preserving.

[...]

The unsigned preserving approach calls for promoting the two smaller unsigned types to unsigned int. This is a simple rule, and yields a type which is independent of execution environment.

The value preserving approach calls for promoting those types to signed int if that type can properly represent all the values of the original type, and otherwise for promoting those types to unsigned int. Thus, if the execution environment represents short as something smaller than int, unsigned short becomes int; otherwise it becomes unsigned int.

在某些情况下,这可能会产生一些相当意外的结果,如 Inconsistent behaviour of implicit conversion between unsigned and bigger signed types事实证明,类似的例子还有很多。尽管在大多数情况下,这会导致操作按预期进行。

关于c++ - 为什么在 C 和 C++ 中算术运算之前必须将 Short 转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24610737/

相关文章:

c++ - 如何在 Visual Studio 2008 中使用 .a lib 文件?

c - Net-SNMP 自定义 MIB 处理程序

java - 将由空格分隔的字符串转换为一行中的整数数组列表

c - 如何正确地将十进制 MIDI 弯音值分成 2 个分开的 7 位值?

java - 从 String[] 中提取数字

c++ - (排列?)通过逐个字符删除字符串

c++ - 如何从 iptables 队列中的数据包中提取源端口号和目标端口号

c - 处理 C 中的不完整类型错误

c++ - 在单个类中具有不同类型名称的同一模板的多个特化

c++ - C++ 中非常特殊的链接器错误