Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 6 Using Decision Structures 171


years old. This has been suggested as an interesting way of relating to dogs, since dogs
have a lifespan of roughly one-seventh that of humans .) The code uses two If statement
conditions and can be used in a variety of different contexts—I used it in the Click event
procedure for a button object. The first condition checks to see whether a non-zero number
has been placed in the HumanAge variable—I’ve assumed momentarily that the user has
enough sense to place a positive age into HumanAge because a negative number would
produce incorrect results. The second condition tests whether the person is at least seven
years old. If both conditions evaluate to True, the message “You are at least one dog year
old” is displayed in a message box. If the person is less than seven, the message “You are
less than one dog year old” is displayed.

Now imagine that I’ve changed the value of the HumanAge variable from 7 to 0. What
happens? The first If statement condition is evaluated as False by the Visual Basic compiler,
and that evaluation prevents the second condition from being evaluated, thus halting, or
short-circuiting, the If statement and saving us from a nasty “divide by zero” error that could
result if we divided 7 by 0 (the new value of the HumanAge variable). And recall that if you
divide by zero in a Visual Basic program and don’t catch the problem somehow, the result
will be an error because division by zero isn’t permitted.

In summary, the AndAlso and OrElse operators in Visual Basic open up a few new possibilities
for Visual Basic programmers, including the potential to prevent run-time errors and other
unexpected results. It’s also possible to improve performance by placing conditions that
are time-consuming to calculate at the end of the condition statement because Visual
Basic doesn’t perform these expensive condition calculations unless it’s necessary. However,
you need to think carefully about all the possible conditions that your If statements might
encounter as variable states change during program execution.

Select Case Decision Structures


With Visual Basic, you can also control the execution of statements in your programs by
using Select Case decision structures. You used Select Case structures in Chapters 3 and 5
of this book when you wrote event procedures to process list box and combo box choices.
A Select Case structure is similar to an If... Then... ElseIf structure, but it’s more efficient
when the branching depends on one key variable, or test case. You can also use Select Case
structures to make your program code more readable.

The syntax for a Select Case structure looks like this:

Select Case variable
Case value1
statements executed if value1 matches variable
Case value2
statements executed if value2 matches variable
Case value3
Free download pdf