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

Asked

Viewed 1,323 times

4

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

Codes like this generate errors with 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 proper incremented numbers:

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

Why then this setting is not enabled by default?

1 answer

5


Definition and use

DelayedExpansion causes variables to be "expanded" (transformed from variable names to values) during the Runtime, that is, during the execution of the code.

The default is that they are "expanded" during the Parsing (before the code is implemented, when the reads what you wrote).

When enabled, you can reference variables using exclamations (!nome!) beyond the ordinary, %nome%.


Example 1

Let’s take an example of them 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 DelayedExpansion well.

When the code goes through parser, the variable %variavel% is "expanded" to its value, defined in the first line, "primeiro".

However, the reference to variavel using the exclamation points (!variavel!) is not expanded yet, as she is with the delay enabled. When code is executed, variavel is set to "segundo" and therefore changes the value of !variavel!. So we have as output:

primeiro segundo

Example 2

Let’s look at another example to clarify:

@echo off

set valor=0
for /l %%G in (1,1,5) do (echo [%valor%] & set /a valor+=1)
echo Total = %valor%

Here, the loop for performs from 1 to 5, going from 1 to 1. However, because the parser has passed the code, there has been the replacement of %valor% for 0, even if that was not our intention. Output gets:

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

However, all is not lost! Using DelayedExpansion, we can get around this misunderstanding:

@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, !valor! is being used and therefore it will only be replaced during code execution. When the for pass through it, it is replaced by the current value of valor (hehe). We then got the output that was expected:

[0]
[1]
[2]
[3]
[4]
Total = 5

Why is not enabled by default?

Honestly, I don’t know. Probably due to performance and code optimization. Larger codes would probably suffer a little if they had to update every iteration all variables while having other instructions to perform.

But you can enable by default by changing the value in the Windows registry if it’s something that bothers you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.