Breaking out of several nested loops (& ANSI C)

Ken Arnold%UCB arnold at ucsfcgl.UUCP
Tue Oct 23 10:21:43 AEST 1984


> ...
> 
> For stand-alone completeness, we're talking about leaving nested loops as
> follows:
> 
>      label:
> 	for (i = 0; i < n; i++)
> 	{       ...
> 		for (j = 0; j < m; j++)
> 		{       ...
> 			if (error)
> 				break label;
> 		}
> 	}
> 
> Jim Gillogly            {vortex, decvax}!randvax!jim

Under this proposal, what does the following code do:

		if (condition)
			goto label;
		...
	label:
		for (i = 0; i < n; i++)
		{       ...
			for (j = 0; j < m; j++)
			{       ...
				if (error)
					break label;
			}
		}

Does the "goto label" go to the top of the for loop, while the "break
label" goes to the bottom?  Or is this semantically incorrect code,
which the compiler should complain about?

What this shows is that we are really talking about two seperate
things, both designated by "<identifier>:".  In C currently, this is a
marker in the code to name a place where control can be transfered.
The proposed addition would use the same syntax to name a loop so that
"break" and "continue" statements can make reference to it.  These two
meanings are not entirely compatible.

So what does it mean to "goto" a block?  Does it mean to go to the
first executable statement inside the block?  Does it mean to go to the
controlling statement of the block (in the above example, to "for (i =
...)") if it has one.  (Note that blocks can exist without controlling
statments; are such blocks nameable, "break"- and "continue"-able?).
And, even with such questions resolved in some fashion, how is the
compiler to know whether "<identifier>:" is a label or a block name?

I will say that I do not like the proposal (if you couldn't have
guessed), but I would like to know precisely what it is I don't like
:->.  I have always wanted a nice way to get out of such nested loops,
but I haven't seen one yet that is as clear as a goto with a good label
name.  And, I might warn those of you who find goto's inherently evil,
that even were this accepted, there are still areas where (at least in
C) a goto is the clearest way to code something, so "goto"s will still
be used, even by style-conscious structure freaks like me.

		Ken Arnold



More information about the Comp.lang.c mailing list