Date: Tue, 11 Aug 2020 23:54:36 +0200
* Bjarne Stroustrup via Liaison:
> What benefits was this supposed to give programmers?
Labels at the end of blocks?
The most common use is an end label in an outer loop, so that it's
possible to continue the loop from within a nested loop.
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (exit_condition(i, j))
goto continue_outer;
}
continue_outer:
;
}
It's a bit unfortunate that there isn't a syntactically cleaner
approach. It's tempting to write this instead because “continue jumps
to the start of the loop”:
for (int i = 0; i < n; ++i) {
continue_outer:
for (int j = 0; j < m; ++j) {
if (exit_condition(i, j))
goto continue_outer;
}
}
But of course that's not equivalent and usually introduces a bug.
(I've been there myself.)
A labeled loop would make the intent perfectly clear:
outer:
for (int i = 0; i < n; ++i) {
continue_outer:
for (int j = 0; j < m; ++j) {
if (exit_condition(i, j))
continue outer;
}
}
If we could get that, there would be far fewer uses for labels at end
of blocks, I think.
> What benefits was this supposed to give programmers?
Labels at the end of blocks?
The most common use is an end label in an outer loop, so that it's
possible to continue the loop from within a nested loop.
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (exit_condition(i, j))
goto continue_outer;
}
continue_outer:
;
}
It's a bit unfortunate that there isn't a syntactically cleaner
approach. It's tempting to write this instead because “continue jumps
to the start of the loop”:
for (int i = 0; i < n; ++i) {
continue_outer:
for (int j = 0; j < m; ++j) {
if (exit_condition(i, j))
goto continue_outer;
}
}
But of course that's not equivalent and usually introduces a bug.
(I've been there myself.)
A labeled loop would make the intent perfectly clear:
outer:
for (int i = 0; i < n; ++i) {
continue_outer:
for (int j = 0; j < m; ++j) {
if (exit_condition(i, j))
continue outer;
}
}
If we could get that, there would be far fewer uses for labels at end
of blocks, I think.
Received on 2020-08-11 16:58:02