Logical Variables

Previously you have seen how the result of a numeric expression can be placed into a variable of type 'Number'. You can also put the result of a logical expression into a variable of type 'Logical'.

Program( ) Number planet = 3; Logical wantearth; Begin wantearth := planet == 3; If wantearth Then EarthSymbol(20) => {160, 100}; EndIf; End;type_log_1.grs type_log_1.png

Logical Constants

There are two logical constants: True and False. A logical may also explicitly be set to Null, which is neither True nor False. A variable with a Null value cannot be used in a test - it will generate a run-time error. Logical variables can be initialised when declared.

Logical wantearth = False, wantvenus = True;

Logical Operators

There are four operators that take logical values as operands. These are :-

p And q | True if both p and q are True | |

p Or q | True if either p or q ( or both ) are True | |

p XOr q | ( exclusive or ) True if either p or q ( but NOT both ) is True | |

Not p | True if p is False and False if p is True |

The logical operators have a lower precedence that the comparison operators, so it is easy to combine the results of comparisons.

[ = check planet number in range =] If n >= 2 And n <= 3 Then PlanetSymbol(n, 20) => {160, 100}; EndIf;

Within the set of logical operators the Not has highest precedence and goes right to left. Next comes the And operator, which goes left to right. Finally the Or and XOr on the same level and goes left to right. As with other expressions these precedence rules can be over-ridden with parentheses.

So "a Or b And c" will evaluate as "a Or ( b And c )".

If a Logical variable contains the Null value any operation using that value will generate a run-time error: with the exception of the equality comparison operators. So it is important to check that it is not Null before using it ( or ensure that it can never be Null ).

The Logical operators make use of a feature called "short circuiting" to avoid unnecessary calculation. If you have an expression like "res := a Or b", if you evaluate 'a' and find it is True then we will know that the result is True whatever the values of 'b' - so 'b' will not be evaluate. The same will work for "res := a And b": if 'a' is False the result will also be False whatever the result for 'b'. This is particularly useful for testing for Null before using a variable.

We can make use of this by having an expression of the form: "a <> Null And a". This will check that 'a' is not null before trying to do the 'And' part ( the part that would generate an error if 'a' were Null ). The result is that Null would be treated as False. Actually, in this particular case you could use the redundant-looking "If a == True Then".