Consider the expression a+b
, which parses as:
┌───┐ │ + │ └───┘ ⠌ ⠡ ⠌ ⠡ ┌───┐ ┌───┐ │ a │ │ b │ └───┘ └───┘
How does a+b*c
parse?
┌───┐ ┌───┐ │ * │ │ + │ └───┘ └───┘ ⠌ ⠡ ⠌ ⠡ ⠌ ⠡ ⠌ ⠡ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │ + │ │ c │ │ a │ │ * │ └───┘ └───┘ └───┘ └───┘ ⠌ ⠡ ⠌ ⠡ ⠌ ⠡ ⠌ ⠡ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │ a │ │ b │ │ b │ │ c │ └───┘ └───┘ └───┘ └───┘
The right-hand side, of course. *
has higher precedence than +
.
Let’s use parentheses. How does (a+b)*c
parse?
┌───┐ ┌───┐ │ * │ │ + │ └───┘ └───┘ ⠌ ⠡ ⠌ ⠡ ⠌ ⠡ ⠌ ⠡ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │ + │ │ c │ │ a │ │ * │ └───┘ └───┘ └───┘ └───┘ ⠌ ⠡ ⠌ ⠡ ⠌ ⠡ ⠌ ⠡ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │ a │ │ b │ │ b │ │ c │ └───┘ └───┘ └───┘ └───┘
The left-hand side, of course. Parentheses mean “do this first”.
NO!
┌───┐ │ * │ └───┘ ⠌ ⠡ ⠌ ⠡ ┌───┐ ┌───┐ │ + │ │ c │ └───┘ └───┘ ⠌ ⠡ ⠌ ⠡ ┌───┐ ┌───┐ │ a │ │ b │ └───┘ └───┘
+
node feeds to the *
node, so +
must execute before *
.
c
before the addition, or after.
┌───┐ │ * │ └───┘ ⠌ ⠡ ⠌ ⠡ ┌───┐ ┌───┐ │ + │ │ c │ └───┘ └───┘ ⠌ ⠡ ⠌ ⠡ ┌───┐ ┌───┐ │ a │ │ b │ └───┘ └───┘
Possible orders of evaluation:
a
, b
, and c
are fetched.
&& ||
,
(in an expression, not as an argument separator)
?:
+ - * / %
<< >> & | ^
< > <= >= == !=
= += -= *= /= %= <<= >>= &= |= ^=
A user-defined operation (e.g., operator+
) does not have order
determined, because it’s a function called with two arguments. The
order of evaluation of function arguments is unspecified.