[英]When does C++11 do arithmetic type conversions relative to operator precedence?
If I have the following code: 如果我有以下代码:
double compute(double val1,
int32_t val2,
int32_t val3,
int32_t val4) {
return val1 + val2 * val3 * val4;
}
How does the C++11 language specify that the multiplication be performed? C ++ 11语言如何指定执行乘法? Eg, are
val1
, val2
, and val3
multiplied as 32 bit integers, according to operator precedence, possibly overflowing, and then converted to a double, or are they multiplied as doubles? 例如,
val1
, val2
和val3
根据运算符优先级乘以32位整数,可能会溢出,然后转换为双精度数,或者将它们乘以双精度数?
In general, what exactly does the standard say on this subject? 通常,该标准在该主题上到底怎么说? Has it changed in subsequent versions of C++ (eg, C++17)?
在后续的C ++版本(例如C ++ 17)中是否进行了更改?
The expression 表达方式
val1 + val2 * val3 * val4
has the type of double
, but the multiplication part is of type int32_t
. 具有
double
类型,但乘法部分为int32_t
类型。 If we apply the rules on how it is evaluated we have 如果我们对评估方法应用规则,我们有
val1 + (val2 * val3 * val4)
because multiplication has a higher precedence, it will be evaluated without considering the type of val1
and since all of the operands have the same type the result type will be the same as the operands. 因为乘法具有更高的优先级,所以将在不考虑
val1
的类型的情况下对其进行评估,并且由于所有操作数都具有相同的类型,因此结果类型将与操作数相同。 That result is then converted to a double
and added to val1
. 然后将该结果转换为
double
并将其添加到val1
。 This behavior has not changed in any of the versions of C++. 在任何C ++版本中,此行为均未更改。
To get the multiplication to happen as double
you need to cast either val2
or val3
to a double, which will make the entire multiplication part evaluated as a double
. 为了使乘法发生为
double
您需要将val2
或val3
转换为double,这会将整个乘法部分评估为double
。 That would look like 看起来像
val1 + (static_cast<double>(val2) * val3 * val4)
the parentheses are not needed but I like using them to show the grouping 不需要括号,但是我喜欢用它们来显示分组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.