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?
If premature completion of any cycle always means that you have to break the enclosing cycle as well, then you don't need any extra flags. The whole thing might just look as follows
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)
break;
}
if (k < 100) break;
}
if (j < 100) break;
}
In my experience, this is what is needed in majority of cases.
Put all the loops in a function and just return instead of break.
sometimes you can use trick like this:
for (i = 0; i < 100 && !flag2; i++) {
for (j = 0; j < 100 && !flag1; j++) {
for (k = 0; k < 100; k++) {
if (k == 50) {
k = 100;
i = 100;
j = 100;
}
}
}
}
or declare addition flag in your loop:
bool end = false;
for(int i =0; i < 1000 && !end; i++) {
//do thing
end = true;
}
it costs only a line but clean, I think.
justin
a little bit of silly self-documenting:
int i, j, k;
int done = 0;
for (i = 0; i < 100 && ! done; i++) {
for (j = 0; j < 100 && ! done; j++) {
for (k = 0; k < 100 && ! done; k++) {
if (k == 50) we_are(done);
}
}
}
//...
void we_are(int *done) {
*done = 1;
}
but really, you shouldn't have three nested for-loops. You should consider refactoring into different functions and improving your program's logic instead of doing this.
While I agree that sometimes goto
really is the best solution, I think that any problem to which goto
is the solution is a result of poor code.
use goto. it's clean and simple.
Just a wee bit better.
int i, j, k;
int flag1 = 0;
int flag2 = 0;
for (i = 0; i < 100 && !flag2; i++) {
for (j = 0; j < 100 && !flag1; j++) {
for (k = 0; k < 100; k++) {
if (k == 50) {
flag1 = 1;
flag2 = 1;
break;
}
}
}
}
But if you really need to have those loops, then it makes sense explicitly declaring in each loop what conditions must hold for it to continue, for readability.