Breaking out of several nested loops (& ANSI C)

W. Dean Stanton stanton at fortune.UUCP
Tue Oct 23 10:35:50 AEST 1984


> > Gee, I thought everyone knew that the most general structured loop is
> > 	startloop ...  on condition (...) leaveloop ... repeatloop
> Gee, finally someone brought up the world-famous
> 	do  { ...  } while { ...  } loop.
> -Ron "DOD Committee to Stop ADA" Natalie

You probably wanted an expression after "while":
	do <statement> while (expression) <statement>
and might have also thought of:
	do <statement> until (expression) <statement>

An interesting generalization of if-then-else, while, and do-until
(even more general than C's for :-) appears in CACM, Aug. 1983 (vol. 26,
number 8), page 572:

	"A Generalized Control Structure and Its Formal Definition"
	by David Lorge Parnas.

The idea was to define a structured "algorithm".  The compiler (or whatever)
can generate whatever gotos are necessary to implement it. 

My sample C syntax for the "it" (iterate) command follows.  Read "it" as
"iterated-if", "then" as my arrow-substitute, *done* as my substitute
for a downward-arrow meaning all done with this "it" (don't iterate), and
*loop* as my substitute for an upward-arrow meaning iterate back to the
first test after "it", "elseif" was chosen to imply that you can string as
many of these as you wish off of one "it", "else" (a la default) is always
taken if you no earlier branch was taken.  [I'm quoting, I can edit it]:

	-- read until "success" but at most numtry times
	count=1;
	read(raw_data, success);
	it	(success)		then	true_data=FUNC(raw_data) *done*
	 elseif	(count < NUM_TRIES)	then	read(raw_data, &success);
	 					count++;		 *loop*
	 else								 *done*
	ti;

If you can't tell, when you it *loop*, you (dare I say it?) go-to the "it".
When you it the *done*, you go-to the ti.  If the redundant calls to read
bother you, too, they fix it with a compile-time flag, "init" (meaning,
"first time through the loop") and even "non init" ("any time except first"):

	-- read until "success" but at most numtry times
	-- COR is conditional || operator (does not evaluate rest unneccessarily
	count=0;
	it	(init COR (not success) && count < NUM_TRIES)
	 				then	read(raw_data, &success);
	 					count++;		 *loop*
	 elseif	(success)		then	true_data=FUNC(raw_data) *done*
	 else								 *done*
	ti;

The compiler handles the "init" by building an initial branch to the read.
Later loops return to the (not success) test.  Neat, huh?

				- W. Dean Stanton, Graphics Software
UUCP:	{decvax!ihnp4,ucbvax!amd,hpda,sri-unix,harpo}!fortune!stanton
USPS:	Fortune Systems Corp, 101 Twin Dolphin Drive, Redwood City, CA 94065
Phone:	(415) 594-2835
"A standard can always be improved. 
 But it won't be; this is why it is a standard." - A. Lesea & R. Zaks



More information about the Comp.lang.c mailing list