Breaking out of several nested loops (& ANSI C)

Geoff Kuenning geoff at desint.UUCP
Sun Oct 14 06:54:25 AEST 1984


I think some people in the pro-break camp are missing some of the pro-goto's
point.  Suppose you are reading this code:

	label1:	for (i = 0;  i < n;  i++) {
		    while (x ()) {
			...
			if (condition)
			    break label1; *or* goto label2;
		    }
		}
	label2:

Assume we have a fairly large program here;  perhaps the outer loop won't
actually fit on a 24-line screen (give me an Ann Arbor, please!).

Now, when you come to the "break" statement, and you want to follow the code
flow, what do you do?  Obviously, you search (upwards) for label1.  Then you
have to fight Bell-style curly-brace conventions to locate the end of the
loop, which is where the next statement executed will actually be found.  What
a pain!

With the unrestricted goto, of course, you have no idea which direction to
search in, so the problem is even worse.  But if, like most modern programmers,
the author used goto's *only* to break out of nested loops, you can count on
a forward search.  And when you find the matching label, you are done!

The disadvantage of unrestricted goto's is not so much program validation as
optimization (quick:  you are compiling the statement at "label2".  What's in
the registers?  What if there's a backwards jump in the code below?).  This
was the reason Dijkstra originally criticized goto's (and, by the way, he
*did* explicitly state that completely goto-less programs were superior--the
title of his 1968 letter to CACM was "Goto's Considered Harmful").

I think that we need a restricted form of the goto (like the break <label>),
but in a syntax that places the target at the next statement executed.  This
would allow compiler writers to do good global optimizations.  One solution
might be to leave the language syntax alone, but add a compiler switch that
says, in effect, that all goto's are of the restricted "break" form, and it
can safely make this assumption when optimizing.  Even better, we could make
that be the default, and require the switch when compiling programs that had
unrestricted goto's.  The advantage of this is that we could call the switch
"-bozo" :-).

-- 
	Geoff Kuenning
	First Systems Corporation
	...!ihnp4!trwrb!desint!geoff



More information about the Comp.lang.c mailing list