Page 1 of 1

For loops: Is there any reason you HAVE to use different tokens?

Posted: 2023-Mar-20, 8:01 am
by Rekrul
The other day while looking for something else, I stumbled across a web page where a user stated that since some other characters can be used as tokens in a For loop, it was possible to create more than 26 nested loops.

The thing is that, other than for readability, there doesn't seem to be any need to use different tokens at all. Tokens only retain their value within a loop, and since a loop needs to complete before the rest of the script continues, that loop is finished when control passes back to the loop above it. And since the child loop's token no longer exists, the parent loop's token is used.

This works perfectly fine;

Code: Select all

@echo off
for %%F in (file*.txt) do (
echo %%F
for /f "delims=" %%F in (%%F) do (
echo %%F
for /l %%F in (1,1,3) do echo %%F
echo %%F
))
It reads each matching file, echoes its name, echoes each line of the file, echos the numbers 1-3, echoes the line again, then does the same thing for the next line, echoing the filename again at the end, before proceeding to the next file.

You'd think that the second loop would screw up, since it uses %%F as both a token and a parameter, but no, it works just fine.

I'll admit that this is a bad example, but despite all three loops using %%F as the token, they all print exactly what they're supposed to print.

Granted, such code would be confusing when using multiple, nested loops, but as far as I can see, there's no valid reason that you can't use the same token for every loop.

Re: For loops: Is there any reason you HAVE to use different tokens?

Posted: 2023-Mar-20, 12:20 pm
by Simon Sheppard
Using extra characters is not about nesting, but about having the option to use more than 26 TOKENS, so for example you might want to parse some data out of a CSV file with more than 26 columns.

Each FOR command instantiates a new instance in memory which inherits all the variables of the parent process. If you re-use the same parameter variable letter as you have here, then it will overwrite the previous value and then, when the FOR loop completes, the instance terminates and you return to the previous instance with the previous %%F value.

However, if you use different variable names for each FOR command, the inner loop will inherit and can use all those values.

So if instead of %%F, you used %%A and %%M and %%Z
You could then have a command like
Echo %%A -- %%M -- %%Z

Even when the script doesn't need all those values at the same time, it is very handy for debugging.
One reason for re-using the same parameter variable, might be to save a tiny bit of memory, but I doubt that will be a measurable performance boost.