LOGICAL OPERATORS

Logical operators combine two Boolean values and return True or False, depending on the result. The following table summarizes Visual Basic’s logical operators.

image

The operators Not, And, and Or are relatively straightforward.

“Xor” stands for “exclusive or,” and the Xor operator returns True if one but not both of its operands is true. The expression A Xor B is true if A is true or B is true but both are not true.

Xor is useful for situations where exactly one of two things should be true. For example, suppose you’re running a small software conference with two tracks so two talks are going on at any given time. Each attendee should sign up for one talk in each time slot but cannot sign up for both because they’re at the same time. Then you might use code similar to the following to check whether an attendee has signed up for either talk 1a or talk 1b but not both:

If talk1a Xor talk1b Then
    ' This is okay
    ...
End If

The AndAlso and OrElse operators are similar to the And and Or operators, except that they provide short-circuit evaluation. In short-circuit evaluation, Visual Basic is allowed to stop evaluating operands if it can deduce the final result without them. For example, consider the expression A AndAlso B. If Visual Basic evaluates the value A and discovers that it is False, the program knows that the expression A AndAlso B is also False no matter what value ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.