问题
I've into curious question (asking it myself while reading a crude piece of code). Let's look at expression:
double a = c*d*e*2/3*f;
where c, d, e, f are initialized variables of type double
. Does standard guarantee that it would be treated as c*d*e*2
(double result) then divided by 3
and multiplied by f
(or some similar behavior). Obviously, 2/3 being calculated to 0 is undesirable.
Which paragraph of standard defines that?
回答1:
Based on the standard
[intro.abstract] - Note 7 (non-normative):
Operators can be regrouped according to the usual mathematical rules only where the operators really are associative or commutative.
Mathematical rule for MDAS is from left to right (considering the associativity and precedence of operators). So it is evaluated as follows:
(((((c * d) * e) * 2) / 3) * f)
回答2:
In a word - yes.
The property you're looking for is called operator associativity. It defines how operators of the same precedence (such as *
and /
) are grouped and ordered when parenthesis aren't present.
In your case, both *
and /
have the same precedence, and are both left-associative - i.e., they are evaluated from left to right. Which means c
would be multiplied by d
, then the result by e
, then the result by 2
(which would be done with floating point arithmetic, since you're multiplying a double
by an int
literal), then divided by 3
(again, using floating point arithmetic) and finally multiplied by f
.
See this cppreference page for additional information.
回答3:
Both *
and /
have the same precedence, and are left-to-right associative, this means that
a*b*c*d
is parsed as
((a*b)*c)*d
and the same is true if you replace any of the *
with /
.
Source: http://en.cppreference.com/w/cpp/language/operator_precedence
来源:https://stackoverflow.com/questions/49506802/order-of-commutative-mathematical-operations