What's the order C++ does in chained multiplication ?
int a, b, c, d;
// set values
int m = a*b*c*d;
What's the order C++ does in chained multiplication ?
int a, b, c, d;
// set values
int m = a*b*c*d;
operator *
has left to right associativity:
int m = ((a * b) * c) * d;
While in math it doesn't matter (multiplication is associative), in case of both C and C++ we may have or not have overflow depending on the order.
0 * INT_MAX * INT_MAX // 0
INT_MAX * INT_MAX * 0 // overflow
And things are getting even more complex if we consider floating point types or operator overloading. See comments of @delnan and @melpomene.
Yes, the order is from left to right.
int m = a * b * c * d;
If you are more interested in the topic of evaluation order or operator precedence, then you might be surprised how some ++ operations behave, even differently with the version of C.
The order is from left to right in this case where
int m=a*b*c*d;
Here, first (a*b) is computed then the result is multiplied by c and then d as shown using parentheses:
int m=(((a*b)*c)*d);
The order is nominally left to right. But the optimizers in C++ compilers I've used feel free to change that order for data types they think they understand. If you overload operator* and the optimizer can't see through your overload, then it can't change the order. But when you multiply a sequence of things (variables, constants, function results, etc.) whose type is double, the optimizer might use the associative and commutative property of real number multiplication as if it were true in float or double multiplication. That can lead to some surprises when least significant bits matter to you.
So far as I understand, the standard allows that optimization, but I am far from a "language lawyer" so my best guess on the standard is not a pronouncement to be trusted (as compared with my experience on what compilers actually do).
There isn't any special "order" it multiplies as shown, left to right.
int m = a * b * c * d;
The order of operations comes into affect when using addition/ subtraction with dividing/ multiplying. Otherwise it is always left to right. Regardless, with the example, the solution would be the same no matter which order they were in.