question on "global" FOR variables.

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
mirrormirror
Posts: 129
Joined: 08 Feb 2016 20:25

question on "global" FOR variables.

#1 Post by mirrormirror » 28 Jul 2016 17:32

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

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: question on "global" FOF variables.

#2 Post by Aacini » 28 Jul 2016 18:21

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

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: question on "global" FOF variables.

#3 Post by dbenham » 28 Jul 2016 20:58

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

mirrormirror
Posts: 129
Joined: 08 Feb 2016 20:25

Re: question on "global" FOR variables.

#4 Post by mirrormirror » 31 Jul 2016 14:57

Thanks to both of you - the example and link to the earlier discussion helped clarify.

Post Reply