A branch is a point at which your program must make a choice. With these data structures, it is now possible to make programs that can have multiple outcomes. You may be familiar with the first type from Algebra, an If-Then statement, or If P then Q. And they work pretty much the same. Another type is the Select Case, this may prove to be easier at times.
Another name for this concept is conditional clauses. Conditional clauses are blocks of code that will only execute if a particular expression (the condition) is true.
If...Then Statement[edit | edit source]
If...Then statements are some of the most basic statements in all of programming. Every language has them, in some form or another. In Visual Basic, the syntax for an If...Then statement is as follows:
If (condition) Then (reaction) End If
- condition - a set of test(s) that the program executes.
- reaction - the instructions that the program follows when the condition returns true. The condition returns true if it passes the test and returns false if it fails the test.
The condition can be anything from
If X = 1 Then MsgBox "X = 1" End If
If InStr(1, sName, " ") > 0 Then sName = """" & sName & """" End If
If there is only one reaction to the condition, the statement can also be expressed without the End If:
If Y + 3 = 7 Then MsgBox "Y + 3 DOES = 7"
There are also other parts to these statements to make them more complex. Two other terms that can be used are Else, and ElseIf.
Else will, if the condition is false, do whatever comes between the Else statement and the End If statement.
ElseIf will, if the condition directly proceeding it is false, check for another condition and go from there.
If..Then..Else Statement[edit | edit source]
The If..Then..Else statement is the simplest of the conditional statements. They are also called branches, as when the program arrives at an "If" statement during its execution, control will "branch" off into one of two or more "directions". An If-Else statement is generally in the following form:
If condition Then statement Else other statement End If
If the original condition is met, then all the code within the first statement is executed. The optional Else section specifies an alternative statement that will be executed if the condition is false. The If-Else statement can be extended to the following form:
If condition Then statement ElseIf condition Then other statement ElseIf condition Then other statement ... Else another statement End If
Only one statement in the entire block will be executed. This statement will be the first one with a condition which evaluates to be true. The concept of an If-Else-If structure is easier to understand with the aid of an example:
Dim Temperature As Double ... If Temperature >= 40.0 Then Debug.Print "It's extremely hot" ElseIf 30.0 <= Temperature And Temperature<=39.0 Then Debug.Print "It's hot" ElseIf 20.0 <= Temperature And Temperature <= 29.0 Then Debug.Print "It's warm" ElseIf 10.0 <= Temperature And temperature <= 19.0 Then Debug.Print "It's cool" ElseIf 0.0 <= Temperature And Temperature <= 9.0 Then Debug.Print "It's cold" Else Debug.Print "It's freezing" End If
Optimizing hints[edit | edit source]
When this program executes, the computer will check all conditions in order until one of them matches its concept of truth. As soon as this occurs, the program will execute the statement immediately following the condition and continue on, without checking any other condition for truth. For this reason, when you are trying to optimize a program, it is a good idea to sort your If..Then..Else conditions in order of descending likelihood. This will ensure that in the most common scenarios, the computer has to do less work, as it will most likely only have to check one or two branches before it finds the statement which it should execute. However, when writing programs for the first time, try not to think about this too much lest you find yourself undertaking premature optimization.
In Visual Basic Classic conditional statements with more than one conditional do not use short-circuit evaluation. In order to mimic C/C++'s short-circuit evaluation, use ElseIf as described in the example above. In fact for complicated expressions explicit If..Then..ElseIf statements are clearer and easier to read than the equivalent short circuit expression.
Select Case[edit | edit source]
Often it is necessary to compare one specific variable against several constant expressions. For this kind of conditional expression the Select Case is used. The above example is such a case and could also be written like this:
Select Case Temperature Case Is >= 40# Debug.Print "It's extremely hot" Case 30# To 39# Debug.Print "It's hot" Case 20# To 29# Debug.Print "It's warm" Case 10# To 19# Debug.Print "It's cool" Case 0# To 9# Debug.Print "It's cold" Case Else Debug.Print "It's freezing" End Select
Unconditionals[edit | edit source]
Unconditionals let you change the flow of your program without a condition. You should be careful when using unconditionals. Often they make programs difficult to understand. Read Isn't goto evil? below for more information.
Exit[edit | edit source]
End a function, subroutine or property and return to the calling procedure or function. Note that in Visual Basic returning from a function and assigning a return value requires two separate statements.
End[edit | edit source]
This simple command ends the execution of the program
Private Sub cmd1_Click() End End Sub
In this example, when the button cmd1 is clicked, the program will terminate. The End command is provided for backward compatibility and is rarely (if ever) needed to end a VB program. The proper way to end a VB program is to release all object references, stop any running timers, and exit out of any executing procedures. In a small program this could mean to simply unload all the forms. When there are no active object references and no code running, VB will terminate the program in a graceful manner. Using End to end the program will terminate the program in an ungraceful manner (some things may not get shut down properly).
Goto[edit | edit source]
Transfer control to the statement after the label (or line number).
Goto Label Dont_Do_Something Label: ...
In Visual Basic the target of a Goto statement must be in the same procedure; this prevents abuse of the feature by making it impossible to jump into the middle of another subroutine.
Isn't Goto Evil?[edit | edit source]
One often hears that Goto is evil and one should avoid using goto. But it is often overlooked that any exit statement which is not the last statement inside a procedure or function is also an unconditional statement - a goto in disguise.
Therefore if you have functions and procedures with more than one exit statement you can just as well use goto. When it comes down to readability the following two samples are almost the same:
Sub Use_Exit Do_Something If Test Then Exit Sub End If Do_Something_Else End Sub Sub Use_Goto is Do_Something If Test Then Goto Exit_Use_Goto End If Do_Something_Else Exit_Use_Goto: End Sub
In the pure structured approach, neither goto nor multiple exit statements are needed:
Sub Use_If is Do_Something If Not Test Then Do_Something_Else End If End Sub
A couple of notes:
- Return is a reserved keyword and can only be used with a matching Gosub and that the Gosub must reside in the same function, sub or property. It cannot be used to return from a function, sub or property - maybe it should read Exit Sub.
- Error handling in Visual Basic does need the use of Goto, but with a different syntax.
- Visual Basic, believe it or not, supports line numbering, so for example Goto 20 is perfectly acceptable if line 20 exists!
- Using Exit instead of Goto as shown above has some side effects. Calling Exit Sub clears a current error state, i.e. it is the equivalent of an Err.Clear.
Compatibility with VB.Net[edit | edit source]
If you are concerned that you might want to port your code to VB.Net without recasting it later you should probably avoid goto altogether.
One alternative is the pseudo loop. Its purpose is to fake a goto target that occurs later in the routine:
Sub Use_PseudoLoop Do 'Start the pseudo loop. Exists only so that you can use Exit Do Try_Something If Test Then Exit Do End If Try_Again If Test Then Exit Do End If Try_Try_Again Loop While False ' will never loop Do_One_Last_Thing End Sub
Of course this example can be recast using If..Then..Else..End If without the need for any Exit statements at all so it is a little artificial:
Sub Use_IfThen Try_Something If Not Test Then Try_Again If Not Test Then Try_Try_Again End If End If Do_One_Last_Thing End Sub
|Previous: Simple Arithmetic||Contents||Next: Loops|