Suppose I need to break out of three or four nested for loops at once at the occurence of some event inside the innermost loop. What is a neat way of doing that?
goto
. This is one of the very few places where goto
is the appropriate tool, and is usually the argument presented why goto
isn't complete evil.
Sometimes, though, I do this:
void foo() {
bar_t *b = make_bar();
foo_helper(bar);
free_bar(b);
}
void foo_helper(bar_t *b) {
int i,j;
for (i=0; i < imax; i++) {
for (j=0; j < jmax; j++) {
if (uhoh(i, j) {
return;
}
}
}
}
The idea is that I get a guaranteed free of bar, plus I get a clean two-level break out of the switch via return.