OPERATORS & PRECEDENCE ORDER
Updated: Mar 30, 2006

Operators and Precedence Order: higher to lower (& for VB strings)

  ^ * / \ SHL SHR MOD INV + - [relational] NOT AND OR XOR

SHL is shift bits left.  5 SHL 3 = 40 = 5 * 8

SHR is shift bits right.  1000 SHR 2 = 250 = 1000 / 4

MOD is modulus.  17 MOD 3 = 2 = remainder of 17 / 3

INV is inverse modulus.  Please see examples in HotTypes.bas

Relational operators used in conditional statements are

  =  <>  >  >=  <  <=

Each operator is located in a precedence order which is used only when a
quantity is both preceeded and followed by an operator.  For example, for b in
a * b / c, precedence order determines whether * or / is processed first.

Note: Some basic compilers have operators of "equal precedence".  A quantity
cannot be preceded and followed by relational operators; thus, there is no
precedence question among the relational operators.  

  a * b / c  multiplies a * b first, then divides by c
  a / b * c  multiplies b * c first, then divides a by (b * c)
  (a / b) * c  divides a by b first, then multiplies by c

The -P switch and the $EQUALPREC ON directive causes (*, /, \) and (+, -) to be
evaluated with equal operator precedence.  Default is OFF, as described above.
Please see Directives and Switches.

$EQUALPREC OFF (default):

  12 - 4 + 4 = 4
  1 / 2 * 2 = 0.25

$EQUALPREC ON

  12 - 4 + 4 = 12
  1 / 2 * 2 = 1

Necessary and Unnecessary Brackets (parentheses)

Brackets are necessary only to over-ride normal operator precedence as shown
above.

  IF a = b AND a$ > b$ THEN

needs no brackets since any relational operator has a higher precedence than
any logical operator.  If (a = b) AND (a$ > b$) were written, there should be
no effect.

  IF (a OR b) AND (c OR d) THEN

needs brackets since OR has lower precedence than AND.  Indeed, without any
brackets, the above is equivalent to (unnecessary brackets added for clarity):

  IF a OR (b AND c) OR d THEN  'same as a OR b AND c OR d 

Nested Precedence Over-Rides

A nested operator precedence over-ride using () example:

  2 * (6 + (4 AND 2)) = 12

Above the precedence of * over + is deferred.  Further, nested in this
precedence over-ride is another -- + should be processed after AND.  Likewise,

  2 * ((4 AND 2) + 6) = 12

Please also be aware that different compilers may return different results for
the same numeric expression.  And both compilers may be right!  Why?  The
compilers may vary in many ways -- rules of precedence, how floating and 
non-floating values are handled, rules for rounding, etc.  The only thing that
matters is that *you* say the result is correct.  So for any compiler, checking
your work is essential.


Copyright 2003-2006 James J Keene PhD
Original Publication: Oct 8, 2003
