开发者

Use a variable in a 'for' loop

开发者 https://www.devze.com 2023-03-13 21:39 出处:网络
I have following code: 开发者_StackOverflow社区@echo off SET ITER=0 for %%i in (%*) do ( SET ITER+=1

I have following code:

开发者_StackOverflow社区
@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?


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

精彩评论

暂无评论...
验证码 换一张
取 消