0

I would like my variable res to be updated inside the loop, but it does not update until after the second iteration.

Here is my code:

@echo off
set /a res=10

:loop
if %res% gtr 100 (
    goto endLoop
) else (
    set /a res=res*10
    rem Here the 'res' shouldn't it be 100?
    echo the result is : %res%
    rem Here the first iteration display 10 not 100.
    goto loop
)

:endLoop
pause > nul

Is there an explanation for this?

Mofi
  • 46,139
  • 17
  • 80
  • 143
ganzo db
  • 9
  • 6
  • Yes. This question probably gets asked 10 times a day. You need to use [delayed expansion](https://ss64.com/nt/delayedexpansion.html) – Squashman Oct 07 '17 at 16:37
  • 1
    Possible duplicate of [Example of delayed expansion in batch file](https://stackoverflow.com/questions/10558316/example-of-delayed-expansion-in-batch-file) – Squashman Oct 07 '17 at 16:39

1 Answers1

2

As an example of usage of delayed expansion here's your modified code:

@Echo Off
SetLocal EnableDelayedExpansion

Set "res=10"

:loop
If %res% Lss 100 (
    Set/A res*=10
    Echo the result is : !res!
    GoTo loop
)

Pause>Nul

There is an alternative without using delayed expansion in this case, but I'd suggest you stick with the former until you are confident enough to understand the order in which things are read and parsed:

@Echo Off

Set "res=10"

:loop
If %res% Lss 100 (
    Set/A res*=10
    Call Echo the result is : %%res%%
    GoTo loop
)

Pause>Nul
Compo
  • 36,585
  • 5
  • 27
  • 39