Terminating Do Loops Early
For all the Do loops studied in this chapter, you can use the Exit Do statement to send program control outside the current loop block. For example:
Do While 1 If Names(i) = TargetName Then Exit Do End If i += 1 Loop
In this code fragment, we search through a list of names held in the Names() array until we find TargetName . Because the If test is logic True, the Then statement block with the Exit Do statement is executed. This sends program control to the statement following the Loop statement.
What is the meaning of the following line?
Do While 1
In this case, Expression1 of the test expression is hard-wired to be logic True. This guarantees that we'll enter the Do While loop. That's the good news. The bad news is that we'll stay in this loop forever unless we find what we're looking for. In other words, what the code is actually saying is
Do While True
thus creating an infinite loop. This loop is constructed in the belief that we'll eventually find a match and the Exit Do statement will terminate the ( otherwise infinite) loop. Loops like this are perfectly acceptable, provided you know an Exit Do statement will eventually be executed.
Nested Do Loops and Exit Do
If you have nested Do loops and use an Exit Do , where does program control go? Does the Exit Do send control out of all the Do loops, or just the one in which the Exit Do appears? Simply stated, an Exit Do sends program control outside of the loop in which the Exit Do statement appears. An example might help you understand what happens:
Do While Temperature < Critical Do While Ph < Acidic If Vat10 = 0 then Exit Do End if Vat10 -= 5 Loop ' Ph < Acidic Temperature = ReadTemp() Loop ' Temperature < Critical
In this code fragment, the outer Do While is controlled by Temperature and Ph controls the inner Do While loop. If Vat10 equals (this is, becomes empty), the Exit Do statement is executed. This sends program control to the
Temperature = ReadTemp()
program statement. Any Exit Do statement can terminate only the loop in which the Exit Do statement appears.