Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 676
user103214 Avatar asked Dec 17 '22 08:12

user103214


2 Answers

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

like image 167
Cameron Skinner Avatar answered Dec 31 '22 00:12

Cameron Skinner


"Order of evaluation" refers to when different subexpressions within the same expression are evaulated relative to each other.

For example in

3 * f(x) + 2 * g(x, y)

you have the usual precedence rules between multiplication and addition. But we have an order of evaluation question: will the first multiplication happen before the second or the second before the first? It matters because if f() has a side effect that changes y, the result of the whole expression will be different depending on the order of operations.

In your specific example, this order of evaluation scenario (in which the resulting value depends on order) does not arise.

like image 24
Ray Toal Avatar answered Dec 31 '22 02:12

Ray Toal