Search code examples
c++operator-keywordoperator-precedence

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;

Solution

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