Operator Precedence

2 * 3 + 4

The above calculation has two solutions. Most people would do the multiplication first and then the addition. As such you would get the value 10. Some people may decide to do the addition first so would get 14.

  1. (2 * 3) + 4 = 10
  2. 2 * (3 + 4) = 14

Which one is correct. The origonal caluculation is ambigious but very common in the way we write down maths. The brackets make our intensions clear as anything inside brackets is always done first (or treated as a seperate calculation). But which one should we go with if the brackets are left out?

This is where operator precednce comes in. * and / have a higher priority than + and -. As such they would always be done first. That way when we get another calculation like this we know exactly how to work it out.

-2 * 3 + 4

The above comes to -2. Why? Well -2 * 3 = -6, add 4 comes to -2. But why did it not mean

-(2 * 3 + 4) = -10

The answer again comes to precedence. The - symbol is next to the -2 and should be taken into consideration first. It is known as a unary operator as it only applies to a single value. Unary operators have a higher precedence than anything else.

In programming we have a number of special operators known as logical and comparative. The table below shows the correct order things must be done in

Order
Type
Examples
1 Brackets anything in () brackets
2 Unary NOT, - / + , !
3 *, / , %, MOD, DIV When applied to two values
4 + , - When applied to two values
5 Comparisons ==, <>, >, <, >=, <=, !=
6 Logical AND , OR , &&, ||
7 Assignment =