Anders Wegge Keller said:
What would be the difference between break and goto be in a case like
this:
int foo (int bar) {
int q, i, x;
for (q = 0 ; q < bar ; q++) {
breakout:
for (i = 0 ; i < bar*q ; i++) {
for (x = 0 ; x < q ; x++) {
if ((x / q) % i == 42) {
goto breakout;
}
}
}
/* It would be clearer to have the label here, but otherwise? */
}
return x % i;
}
Yes, I know that this probably won't compile. I've just cooked it up
in my mail client, but that's beside the point. I just wanted to add
some semblance to a real function.
The idea of a labeled break (or continue, but I'll set that aside
for brevity) is that the label is the name of the loop, not (just)
the name of a specific point in the code. "break foo" and "continue
foo" branch to two different places, but both use the same name to
refer to the loop.
For example:
OUTER:
while (cond) {
INNER:
while (cond) {
if (done_with_inner) {
break INNER; /* could be just "break;" */
}
if (done_with_outer) {
break OUTER;
}
}
}
A goto statement equivalent to "break OUTER;" would have to branch to a
label *following* the outer loop. Furthermore, it would be illegal
(well, a constraint violation) if "OUTER" were not a label that applies
to a loop enclosing the break statement.
This proposal re-uses the existing label syntax. (Perl does the same
thing.)
Another possibility might be to create a new label syntax to be used
only for loops. I don't necessarily suggest using "::" for this, but
if I did, the above would look like:
OUTER::
while (cond) {
INNER::
while (cond) {
if (done_with_inner) {
break INNER; /* could be just "break;" */
}
if (done_with_outer) {
break OUTER;
}
}
}
Then "goto OUTER;" or "goto INNER;" would not be permitted. Ada does
this; it uses the (deliberately ugly) syntax "<<identifier>>" for
labels that can be targets of goto statements, and "identifier:"
for names of loops and blocks.
If this were to be added to C, I'd be ok with re-using the existing
label syntax. As I said, Perl does this, and it doesn't seem to
cause any confusion. (I don't recall ever writing a goto in Perl,
aside from some small test programs.)