Any loop may be terminated or continued early at any point by using the Exit
or Continue
statements.
Exiting
You can stop any loop by exiting early. To do this, you can use the keyword Exit
along with the name of the loop.
Loop | Exit Statement |
---|---|
For | Exit For |
For Each | Exit For |
Do While | Exit Do |
While | Exit While |
Exiting a loop early is a great way to boost performance by only looping the necessary number of times to satisfy the application's needs. Below is example where the loop will exit once it finds the number 2
.
Dim Numbers As Integer() = {1,2,3,4,5}
Dim SoughtValue As Integer = 2
Dim SoughtIndex
For Each i In Numbers
If i = 2 Then
SoughtIndex = i
Exit For
End If
Next
Debug.Print(SoughtIndex)
Continuing
Along with exiting early, you can also decide that you need to just move on to the next loop iteration. This is easily done by using the Continue
statement. Just like Exit
, it is proceeded by the loop name.
Loop | Continue Statement |
---|---|
For | Continue For |
For Each | Continue For |
Do While | Continue Do |
While | Continue While |
Here's an example of preventing even numbers from being added to the sum.
Dim Numbers As Integer() = {1,2,3,4,5}
Dim SumOdd As Integer = 0
For Each i In Numbers
If Numbers(i) \ 2 = 0 Then Continue For
SumOdd += Numbers(i)
Next
Usage Advice
There are two alternative techniques that can be used instead of using Exit
or Continue
.
You can declare a new Boolean variable, initializing it to one value and conditionally setting it to the other value inside the loop; you then use a conditional statement (e.g. If
) based on that variable to avoid execution of the statements inside the loop in subsequent iterations.
Dim Found As Boolean = False
Dim FoundIndex As Integer
For i As Integer = 0 To N - 1
If Not Found AndAlso A(i) = SoughtValue Then
FoundIndex = i
Found = True
End If
Next
One of the objections to this technique is that it may be inefficient. For example, if in the above example N
is 1000000 and the first element of the array A
is equal to SoughtValue
, the loop will iterate a further 999999 times without doing anything useful. However, this technique can have the advantage of greater clarity in some cases.
You can use the GoTo
statement to jump out of the loop. Note that you cannot use GoTo
to jump into a loop.
Dim FoundIndex As Integer
For i As Integer = 0 To N - 1
If A(i) = SoughtValue Then
FoundIndex = i
GoTo Found
End If
Next
Debug.Print("Not found")
Found:
Debug.Print(FoundIndex)
This technique can sometimes be the neatest way to jump out of the loop and avoid one or more statements that are executed just after the natural end of the loop.
You should consider all of the alternatives, and use whichever one best fits your requirements, considering such things as efficiency, speed of writing the code, and readability (thus maintainability).
Do not be put off using GoTo
on those occasions when it is the best alternative.