GOTO inside FOR loop ? Can it be done ?
Posted: 17 Sep 2023 16:45
Hi,
I'm trying to skip a bit of code using a goto inside a for loop
What I want to do is skip to the end of the for loop and do the next iteration
I've made a small test function to try this out
The output of this code is
So what is happening is that it quits the for loop and skips to the labels and starts executing from there.
Even if that's code inside the loop, but it's not looping anymore
So using GOTO in a for loop, only lets you exit the loop ?
For my usage
I guess I could use a IF statement, but I get weird bugs with variable expansion and I don't really know why, is there another way to skip to the next iteration ?
I'm trying to skip a bit of code using a goto inside a for loop
What I want to do is skip to the end of the for loop and do the next iteration
I've made a small test function to try this out
Code: Select all
:setup
:main
Call :GotoInFor-DEMO
GoTo :EOF
:GotoInFor-DEMO
echo.&echo looping through for testing
for /l %%a in (1,1,10) do (
echo start of the loop %%a
echo middle of the loop %%a
echo end of the loop %%a
)
echo.&echo looping through with a goto
for /l %%a in (1,1,10) do (
echo start of the loop %%a
GoTo :UniqueLabelGoToInFor
echo middle of the loop %%a
:UniqueLabelGoToInFor
echo end of the loop %%a
)
echo.&echo looping through with a if goto
for /l %%a in (1,1,10) do (
echo start of the loop %%a
if %%a LSS 5 GoTo :UniqueLabelGoToInFor
echo middle of the loop %%a
:UniqueLabelGoToInFor
echo end of the loop %%a
)
GoTo :EOF
Code: Select all
MoveObject-DEMO.bat
looping through for testing
start of the loop 1
middle of the loop 1
end of the loop 1
start of the loop 2
middle of the loop 2
end of the loop 2
start of the loop 3
middle of the loop 3
end of the loop 3
start of the loop 4
middle of the loop 4
end of the loop 4
start of the loop 5
middle of the loop 5
end of the loop 5
start of the loop 6
middle of the loop 6
end of the loop 6
start of the loop 7
middle of the loop 7
end of the loop 7
start of the loop 8
middle of the loop 8
end of the loop 8
start of the loop 9
middle of the loop 9
end of the loop 9
start of the loop 10
middle of the loop 10
end of the loop 10
looping through with a goto
start of the loop 1
end of the loop %a
So what is happening is that it quits the for loop and skips to the labels and starts executing from there.
Even if that's code inside the loop, but it's not looping anymore
So using GOTO in a for loop, only lets you exit the loop ?
For my usage
I guess I could use a IF statement, but I get weird bugs with variable expansion and I don't really know why, is there another way to skip to the next iteration ?