Use a variable in a 'for' loop

后端 未结 1 549
囚心锁ツ
囚心锁ツ 2020-12-11 09:17

I have following code:

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

The output is (for three arguments):

相关标签:
1条回答
  • 2020-12-11 09:32

    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!
    )
    
    0 讨论(0)
提交回复
热议问题