Breaking out of deeply nested loops

April 2 2007 at 12:54 AM
S

Previously, I've used a flag as a condition for breaking out of each level, but that can get rather awkward. Some would resort to a GOTO command for a clean break, but others would prefer avoiding GOTO. Here is an alternate solution.

If you have a group of nested FOR loops inside an outer DO loop, all you have to do is EXIT DO to break out of everything at once.

In fact, if you need to break out of a deeply nested FOR loop, you can even create a dummy outer DO loop. Make sure you use a condition to end the dummy loop after one repeat. For example, initialize X as 0, and LOOP UNTIL X = 0. The EXIT can be used only if necessary under certain conditions. Otherwise, it should continue executing the code without a break and you wouldn't want to get trapped inside an endless loop.

To break out of nested DO loops, you might use a dummy outer FOR loop that repeats once:
FOR x = 1 to 1

You can't use a dummy WHILE loop since there is no EXIT WHILE command and you can't place WEND inside a nested DO loop.

Example code:

CLS
FOR x = 1 TO 1
DO
DO
DO
PRINT "Inside nested DO loop"
INPUT "Enter to continue or Q to quit:  ", E\$
IF UCASE\$(E\$) = "Q" THEN EXIT FOR
LOOP UNTIL x = 10
LOOP UNTIL x = 10
LOOP UNTIL x = 10
NEXT x
PRINT "Outside FOR loop.  x = "; x
PRINT
w = 0
DO
FOR x = 1 TO 10
FOR y = 1 TO 10
FOR z = 1 TO 10
PRINT "Inside nested FOR loop"
INPUT "Enter to continue or Q to quit:  ", E\$
IF UCASE\$(E\$) = "Q" THEN EXIT DO
NEXT z
NEXT y
NEXT x
LOOP UNTIL w = 0
PRINT "Outside DO loop.  w = "; w

 This message has been edited by Solitaire1 on Apr 2, 2007 6:53 AMThis message has been edited by Solitaire1 on Apr 2, 2007 12:58 AM

 Respond to this message
Responses