bas7qck.hlp (Table of Contents; Topic list)
Hierarchy of Operations
  Expressions and Operators                    Contents  Index  Back
──────────────────────────────────────────────────────────────────────────────
Hierarchy of Operations
 
When several BASIC operators occur in the same statement, they are executed
in the following order:
 
  1. Arithmetic Operations
     a. Exponentiation (^)
     b. Negation (-)
     c. Multiplication and division (*, /)
     d. Integer division (\)
     e. Modulo arithmetic (MOD)
     f. Addition and subtraction (+, -)
 
  2. Relational Operations (=, >, <, <>, <=, >=)
 
  3. Logical Operations
     a. NOT
     b. AND
     c. OR
     d. XOR
     e. EQV
     f. IMP
 
An exception to the order of operations listed above occurs when an
expression has adjacent exponentiation and negation operators. In this
case, the negation is done first. For example, the following statement
prints the value .0625, not -16:
 
   PRINT 4 ^ - 2
 
If the operations are different and are of the same level, the leftmost one
is executed first and the rightmost last, as explained below.
 
   A = 3 + 6 / 12 * 3 - 2          'A = 2.5
 
The order of operations in the preceding example is as follows:
 
   1. 6 / 12   (= 0.5)
   2. 0.5 * 3  (= 1.5)
   3. 3 + 1.5  (= 4.5)
   4. 4.5 - 2  (= 2.5)
 
In a series of additions or a series of multiplications, there is no fixed
evaluation order. Either 3 + 5 or 5 + 6 may be calculated first in the
following statement:
 
C = 3 + 5 + 6
 
Usually this does not cause problems. However, it may cause a problem if
you have a series of FUNCTION procedure calls in your program:
 
C = Incr(X) + Decr(X) + F(X)
 
If any of the three FUNCTION procedures modify X or change shared
variables, the result depends on the order in which BASIC does the
additions. You can avoid this situation by assigning the results of
FUNCTION calls to temporary variables and then performing the addition:
 
T1 = Incr(X) : T2 = Decr(X) : T3 = F(X)
C = T1 + T2 + T3