18

I have a batch file which contains nested loop with continue-like command:

for %%i in (1, 2, 4, 8, 16, 32, 64, 128, 256) do (
    for %%j in (1, 2, 4, 8, 16, 32, 64, 128, 256) do (
        if %%i gtr %%j goto CONTINUE
        test.exe 0 %%i %%j 100000 > "%%i_%%j".txt
        :CONTINUE
        rem
    )
)

But when if statement is true for the first time, it does not iterate further. I only get text files upto 1_256.txt. So it seems that goto CONTINUE has a problem. What is wrong with my batch file?

1
  • 4
    In short, labels (like :CONTINUE) cannot be used inside a loop. Commented Apr 1, 2016 at 17:58

3 Answers 3

23

goto :Label inside of a block of code () like a for loop breaks the block context, so everything after the :Label is treated as being outside of the block. So you need to invert the if condition to not need goto as ths's answer demonstrates, or you place the code fragment with goto and :Label into a subroutine and use call like this:

for %%i in (1, 2, 4, 8, 16, 32, 64, 128, 256) do (
    for %%j in (1, 2, 4, 8, 16, 32, 64, 128, 256) do (
        call :SUB %%i %%j
    )
)
exit /B

:SUB outer inner
if %1 gtr %2 goto CONTINUE
test.exe 0 %1 %2 100000 > "%1_%2.txt"
:CONTINUE
rem
exit /B
Sign up to request clarification or add additional context in comments.

Comments

7

it seems what you are actually trying to accomplish is a poor man's "less or equal than".
In this case, why not use the real "less or equal than", which is LEQ?
Additionally, you seem to want the output of test.exe in the "%%i_%%j".txt file, so don't use echo.

So this would be

for %%i in (1, 2, 4, 8, 16, 32, 64, 128, 256) do (
    for %%j in (1, 2, 4, 8, 16, 32, 64, 128, 256) do (
        if %%i LEQ %%j test.exe 0 %%i %%j 100000 > "%%i_%%j".txt
    )
)

1 Comment

Thanks. That solves my purpose without using any continue-like command. However, I assume, there is no "good" (user-friendly) continue equivalent thing in Windows batch scripting. I think, to accomplish such thing in complex scenario, some "dirty coding trick" is needed.
1

A user-friendly option is to add an IF "ISCONTINUE" layer:

SETLOCAL ENABLEDELAYEDEXPANSION

for %%i in (1, 2, 4, 8, 16, 32, 64, 128, 256) do (
    for %%j in (1, 2, 4, 8, 16, 32, 64, 128, 256) do (

                SET ISCONTINUE=
                if %%i gtr %%j SET ISCONTINUE=1
                SET !ISCONTINUE! NEQ "1" (


                test.exe 0 %%i %%j 100000 > "%%i_%%j".txt


                )

    )
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.