3

I have following code:

@echo off
SET ITER=0
for %%i in (%*) do (
  SET ITER+=1
  ECHO %ITER%
)

The output is (for three arguments):

0
0
0

Expected output:

1
2
3

Why can't I access the updated variable in the for loop?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jacob
  • 41,721
  • 6
  • 79
  • 81
  • 1
    Possible duplicate of [Batch file variables initialized in a for loop](https://stackoverflow.com/questions/691047/batch-file-variables-initialized-in-a-for-loop) – phuclv Nov 09 '17 at 12:16

1 Answers1

5

Expansion of variables with percents is done before a statement/block is executed.
So in your case the complete block is expanded before the echo %ITER% is executed, to constant echo 0.
The variable ITER itself is updated in the loop properly.

To avoid this, you could use the delayed expansion, this works like percent expansion but just in the moment of execution

@echo off
setlocal EnableDelayedExpansion
SET ITER=0
for %%i in (%*) do (
  SET /a ITER+=1
  ECHO !ITER!
)
jeb
  • 78,592
  • 17
  • 171
  • 225