Operator precedence and the order of evaluation plays a major role when two or more operators are used in a statement.
For example: a = b + c * d – e / z;
After executing the above statement, which operator will be evaluated first? Whether
(a = b) or (b + c) or (c * d ) or (d - e)and so on… The solution to this answer can be given by the below operator precedence table.
We can also remember the priorities of a few operators with BODMAS rules. i.e.
- B – Brackets
- O – Order of (or) Power of
- D – Division
- M – Multiplication
- A – Addition
- S – Subtraction
a = b + c * d - e / z
Let’s solve this expression by using the above-given table or the BODMAS rule. The division has higher priority than multiplication and the priority goes with addition, subtraction, and assignment.
- temp1 = e / z
- temp2 = c * d
- temp3 = b + temp2
- temp4 = temp3 – temp1
- a = temp4
Note: In the above expression all the operators, except assignment have the left to right evaluation order that is the reason, why e is divided by z. In the case of the assignment operator, the right-side value is assigned to the left due to the right to left order.
As a good programming practise, we can also change the expression like a = (((b+c) * (d-e)) / z) . Brackets remove the ambiguity and also improve the code readability.