Reputation: 59
I am practicing in batch program, so I am trying to write one include loop and arithmetic instructions. I wrote the following code:
@echo off
SET /a i=1
FOR /F %%A IN ('DIR /B') DO (
SET /a i += %i% + %i% + 4
ECHO %i%)
But the answer in each line is 1!
I tried writing this code with SET /a "i += %i% + %i% + 4"
, but the answer was the same.
I checked here
and here
but I found nothing related to this error.
even I removed the surrounded spaces in the mentioned line, but the answer was the same.
Upvotes: 0
Views: 36
Reputation: 70933
It is not the same set /a i=1
that set /a i = 1
. In the second case, you define a variable with a space in its name.
And if you do not use the /a
arithmetic switch, but set i= 1
, the space after the =
will be included in the value of the variable.
But with this corrections, your problem is other
@echo off
setlocal enabledelayedexpansion
SET /a "i=1"
FOR /F %%A IN ('DIR /B') DO (
SET /a "i+=i+i+4"
ECHO !i!
)
endlocal
When a block of code (code inside parenthesis) is parsed, all variable reads are replaced with the value in the variable before starting to execute the block. So, if you use %i%
inside you block of code, as this variable read has been replaced with the value of the variable before starting to execute, you will not see the changed value echoed to console, but the initial 1
value. The variable is changing its value (the set
is executed), but as the echo
command is not accessing the variable, but using its value before start of the loop, the same value is echoed for all iterations.
If a variable is changed inside a block of code and the changed value needs to be accessed inside the same block of code, delayed expansion needs to be enabled, and syntax changed in the required variable access from %i%
to !i!
to indicate the parser that the access to the variable value should be delayed until execution of the command.
Upvotes: 1