Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

3.15 Logical Operators

So far, we have studied only simple conditions s , uch as count<=10, total>1000 and number <> sentinelValue. Each selection and repetition structure evaluated only one condition with one of the operators >, <, >=, <=, = and <>. To make a decision that relied on the evaluation of multiple conditions, we performed these tests in separate statements or in nested If/Then or If/ThenElse / structures.

To handle multiple conditions more efficiently, Visual Basic provides logical operators that can be used to form complex conditions by combining simple ones. The logical operators are AndAlso, And, OrElse, Or, Xor and Not. We consider examples that use each of these operators.

Suppose we wish to ensure that two conditions are both true in a program before a certain path of execution is chosen. In such a case, we can use the logical AndAlso operator as follows:

If gender = "F" AndAlso age >= 65 Then
    seniorFemales += 1
End If 

This If/Then statement contains two simple conditions. The condition gender="F" determines whether a person is female, and the condition age>=65 determines whether a person is a senior citizen. The two simple conditions are evaluated first, because the precedences of = and >= are both higher than the precedence of AndAlso. The If/Then statement then considers the combined condition

      gender = "F" AndAlso age >= 65 

This condition evaluates to true if and only if both of the simple conditions are true. When this combined condition is true, the count of seniorFemales is incremented by 1. However, if either or both of the simple conditions are false, the program skips the incrementation step and proceeds to the statement following the If/Then structure. The readability of the preceding combined condition can be improved by adding redundant (i.e., unnecessary) parentheses:

        (gender = "F") AndAlso (age >= 65) 

Figure 3.10 illustrates the effect of using the AndAlso operator with two expressions. The table lists all four possible combinations of true and false values for expression1 and expression2. Such tables often are called truth tables. Visual Basic evaluates to true or false expressions that include relational operators, equality operators and logical operators.

Figure 3.10Fig. 3.10 Truth table for the AndAlso operator.

Now let us consider the OrElse operator. Suppose we wish to ensure that either or both of two conditions are true before we choose a certain path of execution. We use the OrElse operator in the following program segment:

If (semesterAverage >= 90 OrElse finalExam >= 90) Then
   Console.WriteLine("Student grade is A")
End If 

This statement also contains two simple conditions. The condition semesterAverage >=90 is evaluated to determine whether the student deserves an "A" in the course because of an outstanding performance throughout the semester. The condition finalExam >= 90 is evaluated to determine whether the student deserves an "A" in the course because of an outstanding performance on the final exam. The If/Then statement then considers the combined condition

(semesterAverage >= 90 OrElse finalExam >= 90) 

and awards the student an "A" if either or both of the conditions are true. Note that the text "Student grade is A" is always printed, unless both of the conditions are false. Figure 3.11 provides a truth table for the OrElse operator.

Figure 3.11Fig. 3.11 Truth table for the OrElse operator.

The AndAlso operator has a higher precedence than the OrElse operator. An expression containing AndAlso or OrElse operators is evaluated only until truth or falsity is known. For example, evaluation of the expression

(gender = "F" AndAlso age >= 65) 

stops immediately if gender is not equal to "F" (i.e., the entire expression is false); the evaluation of the second expression is irrelevant because the first condition is false. Evaluation of the second condition occurs if and only if gender is equal to "F" (i.e., the entire expression could still be true if the condition age>=65 is true). This performance feature for the evaluation of AndAlso and OrElse expressions is called short-circuit evaluation.

Performance Tip 3.2

In expressions that use operator AndAlso, if the separate conditions are independent of one another, place the condition most likely to be false as the leftmost condition. In expressions that use operator OrElse, make the condition most likely to be true the leftmost condition. Each of these techniques can reduce a program's execution time.

The logical AND operator without short-circuit evaluation And ( ) and the logical inclusive OR operator without short-circuit evaluation Or ( ) are similar to the AndAlso and OrElse operators, respectively, with one exception: The And and Or logical operators always evaluate both of their operands. No short-circuit evaluation occurs when And and Or are employed. For example, the expression

(gender = "F" And age >= 65) 

evaluates age>=65, even if gender is not equal to "F".

Normally, there is no compelling reason to use the And and Or operators instead of AndAlso and OrElse. However, some programmers make use of them when the right operand of a condition produces a side effect (such as a modification of a variable's value) or when the right operand includes a required method call, as in the following program segment:

Console.WriteLine("How old are you?")
If (gender = "F" And Console.ReadLine() >= 65) Then
   Console.WriteLine("You are a female senior citizen.")
End If 

Here, the And operator guarantees that the condition Console.ReadLine()>=65 is evaluated, so ReadLine is called regardless of whether the overall expression is true. It would be better to write this code as two separate statements; the first would store the result of Console.ReadLine() in a variable, and the second would use that variable with the AndAlso operator in the condition.

Testing and Debugging Tip 3.2

Avoid expressions with side effects in conditions, as side effects often cause subtle errors.

A condition containing the logical exclusive OR (Xor) operator is true if and only if one of its operands results in a true value and the other results in a false value. If both operands are true or both are false, the entire condition is false. Figure 3.12 presents a truth table for the logical exclusive OR operator (Xor). This operator always evaluates both of its operands (i.e., there is no short-circuit evaluation).

Figure 3.12Fig. 3.12 Truth table for the logical exclusive OR (Xor) operator.

Visual Basic's Not (logical negation) operator enables a programmer to "reverse" the meaning of a condition. Unlike the logical operators AndAlso, And, OrElse, Or and Xor, which each combine two conditions (i.e., they are all binary operators), the logical negation operator is a unary operator, requiring only one operand. The logical negation operator is placed before a condition to choose a path of execution if the original condition (without the logical negation operator) is false. The following program segment demonstrates the logical negation operator:

If Not (grade = sentinelValue) Then
   Console.WriteLine("The next grade is " & grade)
End If 

The parentheses around the condition grade = sentinelValue are necessary, because the logical negation operator (Not) has a higher precedence than the equality operator. Figure 3.13 provides a truth table for the logical negation operator.

Figure 3.13Fig. 3.13 Truth table for the Not operator (logical NOT).

In most cases, the programmer can avoid the use of logical negation by expressing the condition differently with relational or equality operators. For example, the preceding statement can be written as follows:

If grade <> sentinelValue Then
   Console.WriteLine("The next grade is " & grade)
End If 

This flexibility aids programmers in expressing conditions more naturally. The console application in Fig. 3.14 demonstrates the use of the logical operators by displaying their truth tables.

Figure 3.14Fig. 3.14 Logical-operator truth tables.


Lines 9–15 demonstrate operator AndAlso; lines 18–22 demonstrate operator OrElse. The remainder of procedure Main demonstrates the And, Or, Xor and Not operators. We use keywords True and False in the program to specify values of the Boolean data type. Notice that when a Boolean value is concatenated to a String, Visual Basic concatenates the string "False" or "True" on the basis of the Boolean's value.

The chart in Fig. 3.15 displays the precedence of the Visual Basic operators introduced thus far. The operators are shown from top to bottom in decreasing order of precedence.

Figure 3.15Fig. 3.15 Precedence of the operators discussed so far.

  • + Share This
  • 🔖 Save To Your Account