Posts: 799
Threads: 140
Joined: Apr 2022
Reputation:
33
12-05-2025, 01:55 AM
(This post was last modified: 12-05-2025, 01:57 AM by PhilOfPerth.)
Is it "kosher" to exit a sub while inside a loop in the sub, or does it create problems (e.g. stack corruption etc.)?
(no, Pete, I don't mean a submarine)!
Of all the places on Earth, and all the planets in the Universe, I'd rather live here (Perth, Western Australia.)

Please visit my Website at:
http://oldendayskids.blogspot.com/
Posts: 42
Threads: 7
Joined: Mar 2025
Reputation:
3
It's fine. The loop should be in the sub's scope. When you exit the sub everything is cleared except for static variables. If you do it with a function make sure you set the return value first.
Posts: 3,446
Threads: 376
Joined: Apr 2022
Reputation:
345
Caveat: If you have settings to restore, handles to free, mem to deallocate, you may just want to GOTO the cleanup portion of your sub and exit normally, rather than breakout with an EXIT SUB and skip all that.
Posts: 2,910
Threads: 305
Joined: Apr 2022
Reputation:
167
It won't cause a stack space issue if FOR/NEXT or DO/LOOP WHILE/WEND. Stack issue are a result of doing a gosub without a return. GOTO statements within the gosub routine are the usual culprits, and its just bad coding practice to say the least.
I try to limit using EXIT SUB. Granted I need one when the bottom of a subroutine has one or more gosub routines in it.We have to exit before the program flow hits the gosub routine on its way to the end sub statement.
A way to accomplish the same thing as EXIT SUB is a double loop.
Sub Steve
While -1
Do
If Pete = Tremendous Then Exit While
Loop
Rem Blah, blah, blah...
Wend
End Sub
Shoot first and shoot people who ask questions, later.