- [Instructor] Operator precedence is the order
in which operators are evaluated in an expression.
This expression could have different results
depending upon the order in which it is evaluated.
For example, using parentheses
to bind parts of the expression together,
if we give precedence to the addition, we get this result
and if we move the parentheses around a bit,
we get a different result.
And if we remove the parentheses entirely,
we get yet a different result.
The order of evaluation without any parentheses
is that the multiplication happens first,
then the division, then the addition.
It's as if it were parenthesized like this.
The point of understanding operator precedence
is to be aware of the rules.
You don't need to memorize the rules.
There are plenty of handy reference tables available,
but you do need to know that this is how it works.
And ultimately, if you care about the order of evaluation
of an expression, it's always best to use parentheses.
This is an operator precedence table.
I've included a copy of this in the exercise files
or it's easy to find one online.
I keep a laminated copy of this by my workstation.
It shows all the operators available in both C and C++
with the highest precedence operators at the top
and the lowest at the bottom.
The precedence is the order of evaluation.
Operators near the top of the table are evaluated first.
And associativity is the order in which
operands are evaluated within an expression.
Most operands are evaluated left to right
except prefix unary
and assignment operands are evaluated right to left.
It's important to understand operator precedence,
but it's not so important to memorize it.
It's easy to keep a chart near your workstation
for when you need to read someone else's code
who may not have been so considered as to use parentheses.
Most of the time though,
it's a good idea to use parentheses to specify
the order in which your expressions are to be evaluated.
That'll make your job a lot easier
when you want to read the code later.