Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The order of multiplications

What's the order C++ does in chained multiplication ?

int a, b, c, d;
// set values
int m = a*b*c*d;
like image 784
ampawd Avatar asked Jul 25 '15 20:07

ampawd


1 Answers

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.

like image 149
AlexD Avatar answered Nov 04 '22 19:11

AlexD