6.10. Logical OperatorsSo far, we have studied only simple conditions, such as count <= 10, total > 1000 and number <> sentinelValue. Each selection and repetition statement 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...Then...Else statements. 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 And, Or, AndAlso, OrElse, Xor and Not. We consider examples that use each of these operators. Logical And OperatorSuppose 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 And operator as follows: If gender = "F" And 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 And. The If...Then statement then considers the combined condition gender = "F" And age >= 65 This condition evaluates to true if and only if both simple conditions are true. When this combined condition is true, the seniorFemales count is incremented by 1. However, if either or both of the simple conditions are false, the program skips the increment and proceeds to the statement following the If...Then statement. The readability of the preceding combined condition can be improved by adding redundant (i.e., unnecessary) parentheses: (gender = "F") And (age >= 65) Figure 6.17 illustrates the effect of using the And 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.
Logical Or OperatorNow let us consider the Or 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 Or operator as in the following program segment: If (semesterAverage >= 90 Or 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 Or 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 6.18 provides a truth table for the Or operator. The And operator has a higher precedence than the Or operator.
Logical AndAlso and OrElse OperatorsThe logical AND operator with short-circuit evaluation (AndAlso) and the logical inclusive OR operator with short-circuit evaluation (OrElse) are similar to the And and Or operators, respectively, with one exceptionan expression containing AndAlso or OrElse operators is evaluated only until its 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 6.2
Normally, the AndAlso and OrElse operators can be used in place of And and Or. An exception to this rule occurs when the right operand of a condition produces a side effect such as a modification of a variable's value or 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 or false. If operator AndAlso had been used, the call to Console.ReadLine might not be evaluated. It is better to write this code as two separate statementsa first that stores the result of Console.ReadLine() in a variable, and a second that uses the variable with either the operator AndAlso or the operator And in the condition. Error-Prevention Tip 6.6
Logical Xor OperatorA 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 6.19 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).
Logical Not OperatorThe Not (logical negation) operator enables a programmer to "reverse" the meaning of a condition. Unlike the logical operators And, AndAlso, Or, OrElse and Xor, which each combine two conditions (i.e., these 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 logical negation operator is demonstrated by the following program segment: 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 6.20 provides a truth table for the logical negation operator.
In most cases, you can avoid using 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 helps you express conditions more naturally. Logical Operators ExampleThe application in Fig. 6.21 demonstrates the use of the logical operators by displaying their truth tables. Figure 6.21. Logical operator truth tables.
Lines 610 demonstrate operator And; lines 1317 demonstrate operator Or. The remainder of method Main demonstrates the AndAlso, OrElse, Xor and Not operators. We use keywords true and False in the program to specify values of the Boolean type. Note that when a Boolean value is concatenated to a String, Visual Basic concatenates the string "False" or "true" based on the Boolean's value. Summary of Operator PrecedenceThe chart in Fig. 6.22 displays the precedence of the operators introduced so far. The operators are shown from top to bottom in decreasing order of precedence.
|