Logical expressions (also called Boolean expressions) can have only two values; true or false. They generally result from comparisons you make in your DataBasic code. For example, the code:
A EQ 27
tests the variable A to see if it is equal to 27. If it is, the result is true; otherwise the result is false.
Logical expressions are typically used in branching and looping control structures. For example, the IF statement performs one action if a logical expression is true and another if it is false:
IF A EQ 27 THEN B = B + 1 END ELSE A = A + 1 END
This code adds 1 to B if A is equal to 27; otherwise it adds 1 to A.
However, relational, arithmetic and string expressions can all be used as logical expressions:
Non-numeric strings evaluate to false and generate the run-time error
[B16] Non-numeric data when numeric required; zero used
.
Note: This behaviour can be changed with the TRUE.NONNULL compatibility option.
You can use the NOT function to negate (invert) a logical expression.
The following operators can be used to combine logical expressions:
Symbol | Operation | Example |
---|---|---|
AND or & | logical AND | The expression A OR B
is true if A and/or B is true. It is false only if both A and B are
false. |
OR or ! | logical OR | The expression A AND
B is true only if both A and B are true. It is false if A and/or
B is false. |
For example,
IF A EQ 27 AND B > 0 THEN B = B + 1 END ELSE A = A + 1 END
adds 1 to B if both A is equal to 27 and B is greater than 0; otherwise it adds 1 to A. On the other hand,
IF A EQ 27 OR B > 0 THEN B = B + 1 END ELSE A = A + 1 END
adds 1 to B if either A is equal to 27 or B is greater than 0 (or both); otherwise it adds 1 to A.
The behaviour of all these can be changed with the TRUE.BOOL compatibility option.
Logical operators have the lowest precedence and are only evaluated after the other operations have been performed. If two or more operators appear in an expression, the leftmost is performed first.
Parentheses may be included into an expression to alter the precedence. Any logical operation included in parentheses is carried out first. Parentheses can be used to combine two or more logical operations in the same expression and re-define the order in which they are carried out.
A = 16 X = 1 AND A
X evaluates to to 1, because the current value of A is true (non-zero).
A = 4 B = 1 J = 13 Y = B < (A * 2 - 5) AND J > 20
Y evaluates to 0 (false) because, although B < (A * 2 - 5) is true, J > 20 is false. Both expressions would have to be true in order for X to be true.
A = 12 B = 0 C = 400 X = 5 * A AND (B OR C)
Evaluates to 60, because 5 * A equals 60 and the expression within parentheses (evaluated first) is true (C is non-zero); see notes.
Y = X1 AND X2 AND X3
Sets Y to the value of X1 if variables X1, X2 and X3 are all non-zero; otherwise, sets Y to 0.
Y = "XYZ1" MATCHES "4X" AND X
Sets Y to 1 if X is non-zero, because the first expression "XYZ1" MATCHES "4X" is true.