Use the variable in the 'for' loop

I have the following code:

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

Output (for three arguments):

0
0
0

Expected Result:

1
2
3

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

+3
source share
1 answer

Variables with percentages are expanded before the statement / block is executed.
Thus, in your case, the complete block expands to execution echo %ITER%, to a constant echo 0.
The ITER variable itself is updated correctly in the loop.

To avoid this, you can use slow expansion, it works as a percentage extension, but only at runtime

@echo off
setlocal EnableDelayedExpansion
SET ITER=0
for %%i in (%*) do (
  SET /a ITER+=1
  ECHO !ITER!
)
+5
source

All Articles