从我从this question得到的答案来看,似乎C++在从C执行算术运算时继承了将short
转换为int
的要求,我可以请教您一下why这是首先在C中引入的吗?为什么不把这些操作当作short
来做呢?
例如(taken from dyp's suggestion in the comments):
short s = 1, t = 2 ;
auto x = s + t ;
x
将是int型.
从我从this question得到的答案来看,似乎C++在从C执行算术运算时继承了将short
转换为int
的要求,我可以请教您一下why这是首先在C中引入的吗?为什么不把这些操作当作short
来做呢?
例如(taken from dyp's suggestion in the comments):
short s = 1, t = 2 ;
auto x = s + t ;
x
将是int型.
如果我们看一下第6.3.1.8
条Usual arithmetic conversions中的Rationale for International Standard—Programming Languages—C,它说(emphasis mine going forward):
标准中针对这些转换的规则很少 K&;R中的修改:修改以适应添加的 类型和保值规则.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美元.计算也可以是 在"更窄"的类型中由"如果"规则执行,只要相同 得到了最终的结果.显式强制转换始终可以用于获取 所需类型的值
draft C99 standard中的Section 6.3.1.8涵盖了Usual arithmetic conversions,它应用于算术表达式的操作数,例如,第6.5.6 Additive operators节说:
如果两个操作数都是算术类型,则对它们执行usual arithmetic conversions.
我们在第6.5.5 Multiplicative operators节中也找到了类似的文本.对于short操作数,首先从第6.3.1.1 Boolean, characters, and integers节应用integer promotions,该节说明:
如果int可以表示原始类型的所有值,则该值为
Rationale or International Standard—Programming Languages—C号关于integer promotions号的第6.3.1.1
节的讨论实际上更有趣,我将 Select 性地引用b/c,篇幅太长了,无法完整地引述:
实现减少到two major camps个,其特征可能是 作为unsigned preserving and value preserving.
[.]
这unsigned preserving approach人呼吁提拔两个较小的 将UNSIGNED类型转换为UNSIGNED INT.这是一条简单的规则,并产生一个 独立于执行环境的类型.
这value preserving approach个呼吁将这些类型提升到 如果该类型可以正确表示 原始类型,否则用于将这些类型提升为无符号 内部因此,如果执行环境将简短表示为 小于int,则无符号短整型变为int;否则变为 无符号整数.
在某些情况下,这可能会产生一些意想不到的结果,正如Inconsistent behaviour of implicit conversion between unsigned and bigger signed types个例子所示,类似的例子还有很多.尽管在大多数情况下,这会导致操作按预期进行.