C/C++ 中的扩大和缩小规则

Widening and narrowing rules in C/C++

我试图通读 C/C++ 标准,但找不到答案。

假设您有以下代码段:

int8_t m;
int64_t n;

并且在某些时候你执行 m + n,加法本身是一个二元运算符,我认为最有可能发生在这种情况下的是:

  1. 加宽mn大小相同,调用加宽结果m_prime
  2. 执行m_prime + n
  3. Return int64_t
  4. 类型的结果

我试图理解,但是如果我没有执行 m+n 而执行了 n+m 结果会改变(因为可能会有缩小操作而不是扩大操作)。

我找不到标准中阐明这一点的部分(我理解这听起来微不足道)。

谁能告诉我在标准中哪里可以找到这个?或者在像我所暴露的那种情况下一般会发生什么?

我个人一直在看 "Additive operators" 部分,但在我看来它并没有解释发生了什么,指针算术被覆盖了一点,但没有提到隐式应用的一些转换规则。

你可以假设我说的是 C++11,但我认为任何其他标准都会应用相同的规则。

参见第 5 条表达式 [expr]。第 10 点开始

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

后面的分要点是 "If either operand is..."、“...other 应...”、"If both operands ..." 等

具体例子见10.5.2

Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.