0

The syntax of for loop in batch script is as:

for example I want to do something x=6 times

for /l %%a in (1 ,1, 6)

where 1,1,6 means:

  • start = 1
  • increment per step = 1
  • end = 6

Now, I want to know :

  1. Does the start here implies the index and can I keep it 0 also?

  2. If I do the following:

    set counter=0
    for /l %%a in (0 ,%counter% , 6) do (
        GOTO CASE_%counter%
    
        :CASE_0
        // body
    
        :CASE_1
        // body
        .....
        :CASE_6
        //body
    
        GOTO END_SWITCH
    
        :END_SWITCH
        set /A counter=%counter%+1
        if %counter% LEQ 6 (
            GOTO CASE_%counter% 
        )
    )
    pause
    

The above code does not work but if I set counter=1 in the first line in above code it works fine.

So, does it mean that I need to always start my counter from 1? Can I not start it from 0?

Jason Faulkner
  • 6,378
  • 2
  • 28
  • 33
user3020380
  • 23
  • 1
  • 8
  • also take a look to this answer: http://stackoverflow.com/a/27707122/2152082 Especially at the "update" section (delayed expansion) – Stephan Dec 30 '14 at 16:05

3 Answers3

1

The reason your loop isn't working is because you have Counter=0 and are using it as your increment amount. So every time through the loop, it is incremented by 0; hence it will run forever.

Changing Counter=1 will run for 0..6 (7 total times), each time incrementing by 1.


There are some errors in your loop you may want to take a look at. You are incrementing counter within the loop - I don't think this is doing what you want it to do. %%a will be the variable which increments from your defined min/max values and the FOR construct will handle this for you.

Suggested code:

set counter=1
for /l %%a in (0 ,%counter% , 6) do (
    if "%%a"=="0" (
        [do stuff]
    )
    if "%%a"=="1" (
        [do stuff]
    )
    ...
)
Jason Faulkner
  • 6,378
  • 2
  • 28
  • 33
0

in your example, you have told the program to increment in steps of 0, that is why it did not work.

There is no problem with starting with index of 0. Counter of 0 however will not work.

0

The true root cause of your problem is usage of goto within for which is simply not possible; goto breaks the for loop context, so the command interpreter behaves as the commands in the for body were outside of for as soon as a goto is executed.

As a work-around you could place all code of the for body in a sub-routine (let's call it :SUB_SWITCH), and put call :SUB_SWITCH into the for body as the only command.

You can find a similar problem in this post.


To answer your primary question:
Yes, you can start with 0 or any other (integer) value, even negative ones.
(You can even set the increment to 0 to set up an endless loop (however, start must be equal to or less than end for this to work, otherwise the loop does never iterate).)

Community
  • 1
  • 1
aschipfl
  • 33,626
  • 12
  • 54
  • 99