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
- The compiler will evaluate
c()
first, followed by a()
and then b()
, resulting in i = 2 + 1 * 3 = 5
- 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".
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…