- May
- 239
- 2
A bit of a beginner problem perhaps, but something I noticed myself very recently.
It seems that for counted loops (n1 to n2) with a loop variable (e.g. i) that will be used inside the loop that FOR is preferable to DO, even though it's mostly included for CMD.EXE compatibility as per the help.
The reason is that FOR seems to support using the same loop variable name in nested loops while behaving sensibly (i.e. changes to the loop variable in the inner loop does not affect the loop variable used in the outer loop). This is a very desirable property for the sake of code composability and maintenance (the outer loop might for instance call a GOSUB routine and it's not always obvious it will contain an inner loop).
Do I have this right, or did I maybe miss some important detail somewhere?
Also another question, in CMD.EXE batch files the FOR loop variables must have two percent signs while it makes do with only one on the command line. TCC on the other hand seems to work fine with only one percent sign also in batch files. Is this something you can count on or does it just happen to work? Two percent signs work as well with TCC.
Test batch file to illustrate my points regarding nested loops with same loop variable names.
It seems that for counted loops (n1 to n2) with a loop variable (e.g. i) that will be used inside the loop that FOR is preferable to DO, even though it's mostly included for CMD.EXE compatibility as per the help.
The reason is that FOR seems to support using the same loop variable name in nested loops while behaving sensibly (i.e. changes to the loop variable in the inner loop does not affect the loop variable used in the outer loop). This is a very desirable property for the sake of code composability and maintenance (the outer loop might for instance call a GOSUB routine and it's not always obvious it will contain an inner loop).
Do I have this right, or did I maybe miss some important detail somewhere?
Also another question, in CMD.EXE batch files the FOR loop variables must have two percent signs while it makes do with only one on the command line. TCC on the other hand seems to work fine with only one percent sign also in batch files. Is this something you can count on or does it just happen to work? Two percent signs work as well with TCC.
Test batch file to illustrate my points regarding nested loops with same loop variable names.
Code:
@echo off
echo.
ECHO FOR /L
echo.
for /l %val in (1,1,2) do (
echo Outer1 %val
for /l %val in (1,1,2) do (
echo ` `Inner %val
)
echo Outer2 %val
)
echo.
ECHO DO
echo.
do i = 1 to 2
echo Outer1 %i%
do i = 1 to 2
echo ` `Inner %i%
enddo
echo Outer2 %i%
enddo
echo.
ECHO _do_loop testing
echo.
do 3
echo Outer1 %_do_loop
do 3
echo ` `Inner %_do_loop
enddo
echo Outer2 %_do_loop
enddo