C++数学计算中的内部时间变量

Internal temporal variable in mathematic calculation in C++

下面的例子用来说明我的问题:

#include <iostream>
#include <string>

int main()
{

  signed char p;
  signed char temp=100;
  signed char t=4;
  p = (temp+temp+temp+temp)/t;
  std::cout << "Hello, " << int(p)<< "!\n";
}

在上面的代码中,变量p被定义为四个singed char变量的平均值。但是signed char变量(temp+temp+temp+temp)的总和会大于signed char的范围。所以我的问题是 C++ 如何处理这种情况。

However, the sum of the signed char variable (temp+temp+temp+temp) will be larger than the range of signed char.

这并不重要,因为 char 会因为 integral promotion 被提升为 int。可以找到详细信息 here。因此,操作将通过类型 int 完成,您将获得预期的结果。

什么都没发生,因为integral promotion

Prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable. This conversion always preserves the value.

(temp+temp+temp+temp) 将 return 一个整数。

(temp+temp+temp+temp)/t 将在字符范围内。

所以p == temp