Page 1 of 1

question on "global" FOR variables.

Posted: 28 Jul 2016 17:32
by mirrormirror
This is from the help output of "for /?"

Code: Select all

Remember, FOR variables are single-letter, case sensitive, global,
and you can't have more than 52 total active at any one time.

Can anyone explain what this means in practice? For example running the following code using %%a in consecutive loops seems to cause no issues but the "GLOBAL" part of the helpfile leads me to believe that I should only be able to have one active "%%a" variable at a time:

Code: Select all

for %%a in (1, 2) do ((@ECHO a1: %%a) &(CALL :mysub) &(@ECHO a1: %%a))
GOTO:EOF

:mysub
for %%a in (3,4) do (@ECHO a2: "%%a")
GOTO:EOF
Output:

Code: Select all

a1: 1
a2: "3"
a2: "4"
a1: 1
a1: 2
a2: "3"
a2: "4"
a1: 2

Re: question on "global" FOF variables.

Posted: 28 Jul 2016 18:21
by Aacini
That a FOR replaceable parameter be "global" means that a given %%X variable is the same in any other active FOR command, unless a new %%X variable with same name be created, so the original "global" variable is hidden.

Code: Select all

@echo off

for %%a in (One Two) do call :Sub
goto :EOF


:Sub
for /L %%i in (1,1,3) do echo %%i- %%a
exit /B

Output:

Code: Select all

1- One
2- One
3- One
1- Two
2- Two
3- Two

See this post and the previous discussion...

Antonio

Re: question on "global" FOF variables.

Posted: 28 Jul 2016 20:58
by dbenham
Here is another example that might make the important points clearer:

Code: Select all

@echo off
for %%A in (One Two) do (
  echo Within A loop, A is available of course: %%A
  for %%A in (New_A) do (
    echo Within inner A loop, new local value: %%A
  )
  call :sub
  echo(
)
exit /b

:sub
echo within :sub, A is not available: %%A
for %%B in (.) do (
  echo Within :sub B loop, Surprise! original A is available again: %%A
)
exit /b
--OUTPUT--

Code: Select all

Within A loop, A is available of course: One
Within inner A loop, new local value: New_A
within :sub, A is not available: %A
Within :sub B loop, Surprise! original A is available again: One

Within A loop, A is available of course: Two
Within inner A loop, new local value: New_A
within :sub, A is not available: %A
Within :sub B loop, Surprise! original A is available again: Two


Dave Benham

Re: question on "global" FOR variables.

Posted: 31 Jul 2016 14:57
by mirrormirror
Thanks to both of you - the example and link to the earlier discussion helped clarify.