Boolean Operators

Any expression which can be evaluated as being true or false is called a Boolean expression. The most commonly used Boolean operators are, in order of increasing precedence, or, and and not.

  • The result of using the or operator on two operands is True unless both operands are False.
  • The result of using the and operator on two operands is False unless both operands are True.
  • The result of using the not operator is True only if its operand is False.

When coding in Pascal, put brackets round the expressions that need to be evaluated before the Boolean operation. For example,

while (Count <= MAX) and (Total <= 1000) do

If Boolean variables are used, there is neat shorthand code. For example, when using the Boolean variable Found, write until Found instead of until Found = True. The inbuilt Boolean functions eoln (end of line) and eof (end of file) are used similarly and you will see the following code in many programs using files.

while not eof(filename) do

Examples of Precedence

  1. In the expression not eof and (Count <= MAX), not has a higher priority than and (and also occurs before it), so is evaluated first. The expression becomes False when either the end of the file is reached or when Count exceeds its maximum allowed value evaluates to False.
  2. In the following statement, the and operator must act before or.
    if (Total >= 100) or (Total >= 80) and  RegularCustomer then Discount := True;       
    Since and has the greater precedence, no additional brackets are necessary. However, showing the expression with the bracket included,
    if (Total >= 100) or ((Total >= 80) and  RegularCustomer) then Discount := True;
    does no harm and may help other programmers to read and accept the code.
Programming - a skill for life!

Mathematical, Boolean and relational operators