Search code examples
c++evaluationoperator-precedence

Order of evaluation of expression


I've just read that order of evaluation and precedence of operators are different but related concepts in C++. But I'm still unclear how those are different but related?.

int x = c + a * b;    // 31
int y = (c + a) * b;  // 36

What does the above statements has to with order of evaluation. e.g. when I say (c + a) am I changing the order of evaluation of expression by changing its precedence?


Solution

  • The important part about order of evaluation is whether any of the components have side effects.

    Suppose you have this:

    int i = c() + a() * b();
    

    Where a and b have side effects:

    int global = 1;
    
    int a() {
        return global++;
    }
    int b() {
        return ++global;
    }
    int c() {
        return global * 2;
    }
    

    The compiler can choose what order to call a(), b() and c() and then insert the results into the expression. At that point, precedence takes over and decides what order to apply the + and * operators.

    In this example the most likely outcomes are either

    1. The compiler will evaluate c() first, followed by a() and then b(), resulting in i = 2 + 1 * 3 = 5
    2. The compiler will evaluate b() first, followed by a() and then c(), resulting in i = 6 + 2 * 2 = 10

    But the compiler is free to choose whatever order it wants.

    The short story is that precedence tells you the order in which operators are applied to arguments (* before +), whereas order of evaluation tells you in what order the arguments are resolved (a(), b(), c()). This is why they are "different but related".