Simple Processing: Operator Precedence

Now you know the basic mathematical operators you need to know what order they are calculated in (the so called operator precedence). PureBasic follows the same rules as mathematics in this respect so that multiplication and division operators are evaluated first (and in the order they are written - left to right - if they are beside each other). Addition and subtraction operators are then calculated (also in the left to right order if they are side by side).

For example, given the following calculation:

a = b + c - d + e * f * g / h
Then the order the parts of the calculation are worked out in are as follows:
  1. e * f
  2. ... * g
  3. ... / h
  4. b + c
  5. ... - d
  6. Finally the two parts of the calculation are added together and assigned to the variable a.

Thankfully you can change the order in which calculations are worked out. This is done by putting brackets around parts of the calculation to force it to be calculated first. You can also put brackets inside brackets to force the order of evaluation. The example below shows some applications of operator precedence and brackets. You can find the source here

OpenConsole()

a = 3
b = 5
c = 2
d = 7

; Different operators - multiplication before addition
e = a + b * c
PrintN("The value of e should be 13: "+Str(e))

; Changing the order of evaluation
e = (a + b) * c
PrintN("E should now be 16: "+Str(e))

; Multiple operators of same precedence - from left to right
e = a + b - c
PrintN("E should now be 6: "+Str(e))

DefType.f f

; Multiple operators of same precedence - from left to right
f = a / b * c
PrintN("f = "+StrF(f)+" (should be 1.2)")

; Changing the order of evaluation - but ends up the same since
; the position of the brackets mean the same order is followed
f = (a / b) * c
PrintN("f = "+StrF(f)+" (should be 1.2)")

; Changing the order of evaluation
f = a / (b * c)
PrintN("f = "+StrF(f)+" (should be 0.3)")

; Nested brackets
f = (a - ((b + d) / (c + d)))
PrintN("f = "+StrF(f)+" (should be 1.6666...)")

; Without brackets
f = a - b + d / c + d
PrintN("f = "+StrF(f)+" (should be 8.5C)")

PrintN("Press return to exit")
Input()
CloseConsole()
End

Output of the brackets example