Search code examples
c++operatorslanguage-lawyertype-promotion

Order of commutative mathematical operations


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?


Solution

  • 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)