Precedence
Arithmetic, relational and logical operators work in a specific order or precedence.
For instance, most people are familiar with an example like the following:
a = 5 * 10 + 2
What is the value of a after this assignment?
It should be 52, why? Because the * (multiplication) operator has a higher precedence than the + (addition). This means that the interpreter scans the line until it hits the plus sign, then returns the result of the multiplication before doing the addition.
Precedence can be altered by using the parentheses. If the assignment is changed to:
a = 5 * ( 10 + 2 )
The result stored in a would be 60 (5 * 12), the precedence of the plus sign has been moved higher than the multiplication because the addition was grouped in parentheses.
Precedence usually follows a pattern of math operators being highest, then relational operators, then logical operators.
Here is natural arithmetic, relational and logical precedence from highest to lowest.
You can alter this using parentheses as explained above.
!, NOT - unary not, as in !( I % 2) - parentheses are required here!!
- - negation as in -1 * 10 - This is different from subtraction, answer is -10
^ - exponentiation as in 10^2 * 5 - answer is 500, not 10 billion
*, / - multiplication and division
+, - - addition and subtraction
% - Modulo, the lowest math operator.
Modulo having the lowest precedence is the reason parens are needed around the statement !( I % 2 ). If there were no parens, the NOT operator would be applied immediately to I and would return zero if I was non zero, the intent was to determine if I was even or odd.
<>, <=, >=, == - All of the relational operators go here.
AND, OR - A logical AND or OR have the (SAME) lowest precedence, so it should not be necessary to structure expressions with parens, UNLESS you are chaining together AND's and OR's in the same expression.
= Last, and least the assignment operator has the lowest precedence of all.
An example showing the effect of equal precedence for AND and OR mixed in an expression:
IF LEN( A ) > 10 AND MID( A, 1, 1 ) == "A" OR MID( A, 1, 1 ) == "B" THEN
This line will produce the same result if written as:
IF ( LEN( A ) > 10 AND MID( A, 1, 1 ) == "A" ) OR MID( A, 1, 1) == "B" THEN
so the condition is actually:
if A is longer than 10 characters and the first letter is "A" then expression is true, OR if the first letter in A is "B" it is true regardless of how long or short the string is.
depending on the intent, precedence could be enforced as follows:
IF LEN( A ) > 10 AND ( MID( A, 1, 1 ) == "A" OR MID( A, 1, 1) == "B" ) THEN
The condition is interpreted as:
If A is longer than 10 characters and the first letter is either "A" or "B" then the expression is true.