What is DelayedExpansion and why is it not enabled by default?

3

Generally when creating a batch that uses any block of code, such as loops for or if , we end up going through this problem and then we discover the need to set EnableDelayedExpansion .

Codes like this generate errors at each iteration:

@echo off
setlocal
set cont=0
FOR /l %%G in (1,1,5) Do (
    echo [%cont%]
    set /a cont+=1
 )
echo Total = %cont%

Output without due incremented numbers:

[0]
[0]
[0]
[0]
[0]
Total = 5

Why is not this setting enabled by default?

    
asked by anonymous 22.02.2017 / 13:48

1 answer

3

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.

    
25.02.2017 / 05:37