Section 6.10. Logical Operators


6.10. Logical Operators

So 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 Operator

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 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.

Figure 6.17. Truth table for the logical And operator.

expression1

expression2

expression1 And expression2

False

False

False

False

true

False

true

False

False

true

TRue

true


Logical Or Operator

Now 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.

Figure 6.18. Truth table for the logical Or operator.

expression1

expression2

expression1 or expression2

False

False

False

False

true

true

true

False

true

true

true

true


Logical AndAlso and OrElse Operators

The 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

In expressions using 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 using operator OrElse, make the condition most likely to be true the leftmost condition. Each of these suggestions can reduce a program's execution time.


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

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


Logical Xor Operator

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 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).

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

expression1

expression2

expression1 Xor expression2

False

False

False

False

true

true

true

False

true

TRue

TRue

False


Logical Not Operator

The 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.

Figure 6.20. Truth table for operator Not (logical negation).

expression

Not expression

False

true

TRue

False


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 Example

The application in Fig. 6.21 demonstrates the use of the logical operators by displaying their truth tables.

Figure 6.21. Logical operator truth tables.

  1  ' Fig. 6.21: LogicalOperators.vb  2  ' Using logical operators.  3  Module LogicalOperators  4     Sub Main()  5        ' display truth table for And  6         Console.WriteLine("And" & vbCrLf & _  7            "False And False: " & (False And False) & vbCrLf & _  8            "False And True: " & (False And True) & vbCrLf & _  9            "True And False: " & (True And False) & vbCrLf & _ 10            "True And True: " & (True And True) & vbCrLf) 11 12         ' display truth table for Or 13         Console.WriteLine("Or" & vbCrLf & _ 14            "False Or False: " & (False Or False) & vbCrLf & _ 15            "False Or True: " & (False Or True) & vbCrLf & _ 16            "True Or False: " & (True Or False) & vbCrLf & _ 17            "True Or True: " & (True Or True) & vbCrLf) 18 19         ' display truth table for AndAlso 20         Console.WriteLine("AndAlso" & vbCrLf & _ 21            "False AndAlso False: " & (False AndAlso False) & vbCrLf & _ 22            "False AndAlso True: " & (False AndAlso True) & vbCrLf & _ 23            "True AndAlso False: " & (True AndAlso False) & vbCrLf & _ 24            "True AndAlso True: " & (True AndAlso True) & vbCrLf) 25 26         ' display truth table for OrElse 27         Console.WriteLine("OrElse" & vbCrLf & _ 28            "False OrElse False: " & (False OrElse False) & vbCrLf & _ 29            "False OrElse True: " & (False OrElse True) & vbCrLf & _ 30            "True OrElse False: " & (True OrElse False) & vbCrLf & _ 31            "True OrElse True: " & (True OrElse True) & vbCrLf) 32 33         ' display truth table for Xor 34         Console.WriteLine("Xor" & vbCrLf & _ 35            "False Xor False: " & (False Xor False) & vbCrLf & _ 36            "False Xor True: " & (False Xor True) & vbCrLf & _ 37            "True Xor False: " & (True Xor False) & vbCrLf & _ 38            "True Xor True: " & (True Xor True) & vbCrLf) 39 40         ' display truth table for Not 41         Console.WriteLine("Not" & vbCrLf & "Not False: " & _ 42            (Not False) & vbCrLf & "Not True: " & (Not True) & vbCrLf) 43     End Sub ' Main 44  End Module ' LogicalOperators 

 And False And False: False False And True: False True And False: False True And True: True Or False Or False: False False Or True: True True Or False: True True Or True: True AndAlso False AndAlso False: False False AndAlso True: False True AndAlso False: False True AndAlso True: True OrElse False OrElse False: False False OrElse True: True True OrElse False: True True OrElse True: True Xor False Xor False: False False Xor True: True True Xor False: True True Xor True: False Not Not False: True Not True: False 



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 Precedence

The 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.

Figure 6.22. Precedence of the operators discussed so far.

Operators

Type

^

exponentiation

+ -

unary plus and minus

* /

multiplicative operators

\

integer division

Mod

modulus

+ -

additive operators

&

concatenation

< <= > >= = <>

relational and equality

Not

logical NOT

And AndAlso

logical AND

Or OrElse

logical inclusive OR

Xor

logical exclusive OR

= += -= *= /= \= ^= &=

assignment




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net