Vinod Chelladurai
Vinod Chelladurai

Reputation: 539

Windows Batch file processing - Loops

Am very new to batch scritping. I just tried to execute the below code for which am totally confused.

@echo off
set m=100
set i=0
FOR /L %%N IN (0,1,%m%)do (
set /a i=1+%i%
)

echo %i% pause

Here, am incrementing i value until N reaches 100. So, am expecting the value of i at the end of loop to be 101 but it shows 1. Can anyone explain what's the reason behind this.

thanks

Upvotes: 2

Views: 220

Answers (2)

MC ND
MC ND

Reputation: 70923

In batch files, variable reads are replaced with their values at parse time, before executing the line or the block (code enclosed in parenthesis).

So, the %i% reference inside the for loop is replaced with the value of the variable before the for loop, that is, 0 , and %m% is replaced with 100, and what gets executed is

for /l %%n in (0 1 100) do ( set /a i=1+0 )

You can enable delayed expansion (setlocal enabledelayedexpansion command) and change the sintax from %i% to !i! to indicate the parser that reads to the variable should be delayed until the moment of executing the line. The code should be

@echo off
  setlocal enabledelayedexpansion
  set m=100
  set i=0
  FOR /L %%N IN (0,1,%m%)do (
    set /a i=1+!i!
  )
  echo %i%
  endlocal

The read of the value of i inside the for loop is delayed. This way, the real value is readed just before each execution of the line. Reference to i out of the loop does not need it. When the line is reached and parsed, the correct value is retrieved and echoed.

Anyway, while this is the general rule, set /a has a different behaviour. If you change your code to

set /a i+=1

or

set /a i=i+1

the parser will correctly identify the operation and execute the expected code with or without delayed expansion enabled.

Upvotes: 2

npocmaka
npocmaka

Reputation: 57252

You need delayed expansion : http://www.robvanderwoude.com/variableexpansion.php

@echo off
setlocal enableDelayedExpansion
 set m=100
 set i=0
 FOR /L %%N IN (;;0,1,%m%;;) do (
   set /a i=1+!i!
 )
endlocal & set /a i=%i%
echo %i%

Upvotes: 2

Related Questions