Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

3.14 Using the Exit Keyword in a Repetition Structure

The ExitDo, ExitWhile and ExitFor statements alter the flow of control by causing immediate exit from a repetition structure. The ExitDo statement can be executed in a Do While/Loop, Do/Loop While, Do Until/Loop or Do/Loop Until structure and causes the program to exit immediately from that repetition structure. Similarly, the Exit For and Exit While statements cause immediate exit from For/Next and While loops, respectively. Execution continues with the first statement that follows the repetition structure. Figure 3.9 demonstrates the ExitFor, ExitDo and ExitWhile statements in various repetition structures.

Figure 3.9Fig. 3.9 Exit keyword in repetition structures.


The header of the For/Next structure (line 12) indicates that the body of the loop should execute 10 times. During each execution, the If/Then structure (lines 15–17) determines if the control variable, counter, is equal to 3. If so, the ExitFor statement (line 16) executes. Thus, as the body of the For/Next structure executes for the third time (i.e, counter is 3), the ExitFor statement terminates execution of the loop. Program control then proceeds to the assignment statement (lines 21–22), which appends the current value of counter to String variable output.

The header of the DoUntil/Loop structure (line 24) indicates that the loop should continue executing until counter is greater than 10. (Note that counter is 3 when the DoUntil/Loop structure begins executing.) When counter has the values 3 and 4, the body of the If/Then structure (lines 27–29) does not execute, and counter is incremented (line 31). However, when counter is 5, the Exit Do statement (line 28) executes, terminating the loop. The assignment statement (lines 34–35) appends the value of counter to String variable output. Note that the program does not increment counter (line 31) after the ExitDo statement executes.

The While structure (lines 37–45) behaves similarly to the DoWhile/Loop. In this case, the value of counter is 5 when the loop begins executing. When counter is 7, the ExitWhile statement (line 41) executes, terminating execution of the While structure. Lines 47–48 append the final value of counter to String variable output, which is displayed in a message dialog (lines 50–51).

Software Engineering Observation 3.1

Some programmers feel that Exit Do, Exit While and Exit For violate the principles of structured programming.

Software Engineering Observation 3.2

Debates abound regarding the relative importance of quality software engineering and pro-accomplished at the expense of the other. For all but the most performance-intensive situations, apply the following guidelines: First, make your code simple and correct; then make it fast and small, but only if necessary.

  • + Share This
  • 🔖 Save To Your Account