infinite loop with break condition

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Posts: 3667
Joined: 22 Jan 2010 18:01
Location: Germany

Re: infinite loop with break condition

#31 Post by aGerman » 01 Jan 2012 07:58

Hi Rileyh.

Read the entire thread to understand how it works.

GOTO is slow and "evil". A lot of programming languages don't support GOTO. The only reason why you need GOTO in batch files is to create loops. If you use it to jump forward to a label in bigger files then you finally create unmaintainable spaghetti code!

The macro stuff is only a goody and uses the EXIT <ReturnValue> method we figured out before.


Ed Dyreen
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)

Re: infinite loop with break condition

#32 Post by Ed Dyreen » 15 Jan 2012 20:58


I come in a little late on this topic, just wanted to say I've been using the while idea for a while.
I do want to point out it is going to be difficult (not impossible) to evaluate very complex conditions if while is in the form of a macro.
Therefor I use a while function, the condition that is tested comes as a macro reference executed by the while, optionally setting a timeout:

Code: Select all

( %While% @condition, $timeout ) &&echo.succes ||echo.timeout !
Having while as a function allows me to use any macro as a condition.
No need to explain any further, you know where to find the source-code ( I assume ) :wink:

Posts: 1611
Joined: 06 Dec 2011 22:15
Location: México City, México

Re: infinite loop with break condition

#33 Post by Aacini » 23 May 2012 22:44

Although this topic was solved already, the definition of the While macro is not very practical. I devised another way to made a While easier to write and use.

Code: Select all

@echo off

rem While dispatcher
if "%1" equ "While" goto While%2

setlocal EnableDelayedExpansion

rem Definition of auxiliary variables
set While=for /L %%a in () do if
set Do=(
set EndW=) else exit
set RunWhile=cmd /V:ON /Q /C "%0" While

echo Example of While
goto RunWhile1

rem Write the While code here
set /A i=0, num=0
set /P "num=Enter number: "
%While% !num! gtr 0 %Do%
   set /A i+=1
   echo !i!- Number processed: !num!
   set num=0
   set /P "num=Enter number: "
%EndW% !i!

rem Execute the While here
%RunWhile% 1
set i=%errorlevel%
echo While processed %i% elements


PS: A new way to write a WHILE macro is described here.

Post Reply