Exiting a FOR/NEXt loop
#1
Hi all. First post. I did post a couple of times on Facebook, but now I'm here.
Okay... I have a FOR/NEXT loop that I want to exit if a certain condition occurs. The thing is, if I put a label for it to go to it doesn't do that. It simply resumes on the next line after the loop. I'm using version 2.02

Code: (Select All)
Cls
For x& = 1 To 10
    Print x&
    If x& = 5 Then Exit For: GoTo stuff
Next x&

Print "done"
here: GoTo here

stuff:
Print "exited loop"
Reply
#2
You EXIT FOR, which moves the program flow at that point to after the NEXT statement. The GOTO never executes.

For x& = 1 To 10
Print x&
If x& = 5 Then Exit For: GoTo stuff
Next x&

PRINT x& ' As you can see here, x& is 5, so you did indeed EXIT the FOR loop.
Print "done"
Reply
#3
It certainly did exit the loop. I'm just surprised that it didn't treat the GOTO following the colon as the next instruction and follow it instead. Just now I tried it on QBASIC and it does the same thing. Oh well...
Reply
#4
(08-24-2022, 06:17 AM)Circlotron Wrote: It certainly did exit the loop. I'm just surprised that it didn't treat the GOTO following the colon as the next instruction and follow it instead. Just now I tried it on QBASIC and it does the same thing. Oh well...
This is what you expected the program to do:
Code: (Select All)
Cls
For x& = 1 To 10
    Print x&
    If x& = 5 Then Exit For
Next x&

If x& = 5 Then GoTo stuff

Print "done"
here: GoTo here

stuff:
Print "exited loop"
Check out the line right below "next x&"...
Reply




Users browsing this thread: 2 Guest(s)