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?
I'd do something like:
int i, j, k;
for (i = 0; i < 100; i++) {
for (j = 0; j < 100; j++) {
for (k = 0; k < 100; k++) {
if (k == 50) {
return;
}
}
}
}
How would you accomplish the same thing? (w/o using jumps)
Why? Nothing is universally evil, and every put-upon tool has its uses (except gets()
). Using goto
here makes your code look cleaner, and is one of the only choices we have (assuming C). Look:
int i, j, k;
for (i = 0; i < 100; i++) {
for (j = 0; j < 100; j++) {
for (k = 0; k < 100; k++) {
if (k == 50) {
goto END;
}
}
}
}
END:
Much cleaner than all those flag variables, and it even shows more clearly what your code is doing.