Next: Examples of Arithmetic Expressions Up: The Assignment statement Previous: The Assignment statement

Priority of Operators

Another problem associated with evaluating expressions is that of order of evaluation. Should

a + b * c
be evaluated by performing the multiplication first, or by performing the addition first? i.e. as
(a + b) * c or as a + (b * c) ?

C++ solves this problem by assigning priorities to operators, operators with high priority are then evaluated before operators with low priority. Operators with equal priority are evaluated in left to right order. The priorities of the operators seen so far are, in high to low priority order:

( )
* / %
+ -
=
Thus
a + b * c
is evaluated as if it had been written as
a + (b * c)
because the * has a higher priority than the +. If the + was to be evaluated first then brackets would need to be used as follows:
(a + b) * c

If in any doubt use extra brackets to ensure the correct order of evaluation.

It is also important to note that two arithmetic operators cannot be written in succession, use brackets to avoid this happening.



Next: Examples of Arithmetic Expressions Up: The Assignment statement Previous: The Assignment statement