Definition and use
DelayedExpansion
causes variables to be "expanded" (transformed from variable names to values) during runtime , that is, during code execution.
The default is that they are "expanded" during parsing (before the code is executed, when the program actually reads what you wrote). >
When enabled, you can reference the variables using exclamations (% with%) in addition to the common,% with%.
Example 1
Let's look at an example of this in action:
@echo off
setlocal EnableDelayedExpansion
set variavel=primeiro
set variavel=segundo & echo %variavel% !variavel!
The above code may seem simple, but it represents the effect of !nome!
as well.
When the code passes through the parser , the variable %nome%
is "expanded" to its value, defined in the first line, DelayedExpansion
.
However, the reference to %variavel%
using the exclamation points ( "primeiro"
) is not expanded yet, since it has delay enabled. When the code is executed, variavel
is set to !variavel!
and therefore changes the value of variavel
. So, we have as output:
primeiro segundo
Example 2
Let's look at another example to clarify further:
@echo off
set valor=0
for /l %%G in (1,1,5) do (echo [%valor%] & set /a valor+=1)
echo Total = %valor%
Here, the "segundo"
loop runs from 1 to 5, going from 1 to 1. However, because the parser has already passed the code, there has already been a substitution of !variavel!
with for
, even if that was not our intention. The output is:
[0]
[0]
[0]
[0]
[0]
Total = 5
But all is not lost! Using %valor%
, we can work around this misconception:
@echo off
setlocal EnableDelayedExpansion
set valor=0
for /l %%G in (1,1,5) do (echo [!valor!] & set /a valor+=1)
echo Total = %valor%
Here, 0
is being used, so it will only be overwritten during code execution. When DelayedExpansion
passes through it, it is replaced by the current value of !valor!
(hehe). We were then left with the output that was expected:
[0]
[1]
[2]
[3]
[4]
Total = 5
Why is it not enabled by default?
Honestly, I do not know. Probably due to performance and code optimization. Larger codes would probably suffer a little if they had to update every iteration at each iteration while they have other instructions to perform.
But you can enable by default by changing the value in the Windows registry, if that is something that bothers you.