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 Usual arithmetic conversions 部分中它说(强调我的前进):

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.

Rationale or International Standard—Programming Languages—C部分6.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/47774161/

相关文章:

c++ - 将 boost::dynamic_bitset<> 插入 boost::bimap

c++ - Winsock延迟,测试连接速度

c - 如何在 C 编程中根据 char 变量命名结构

java - 使用 JNI 从 java 调用 C 函数

c# - LINQ 检查是否为 int?在 List<Int> C# 中

firebase - Flutter Firebase更新不会停止更新节点?

android - 在 Sqlite android 中插入整数值

c++ - 在 C++ 中表示关系

我可以将结构数组发送到其他函数吗? C语言

c++ - 取回失败的输出