Home > Articles > Programming > Windows Programming

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020