Oops! The title says it all! Does anyone know an interesting way to get out of more than one loop without using goto?
Oops! The title says it all! Does anyone know an interesting way to get out of more than one loop without using goto?
In C it is possible to have a control variable that is part of the expression of for
- you arrow it in the innermost loop, and this leaves the expressions of the outermost loops false. Only the code after the end of the innermost loop, but inside the outer loops will be executed one last time, unlike what would happen with a goto
or an exception.
int finished = 0;
for (int i=0; !finished && i < 640; i++)
for (int j=0; !finished && j < 480; j++)
for (int k=0; !finished && k < 4; k++) {
...
if (condition) {
...
finished = 1;
}
}
Interesting not. You can use a long jump in C or raise an exception in C ++, but are much worse options than goto
.
So, if you can not create a situation where the loop closes naturally (it always does, but you have to make it too confusing and it might be better to do it artificially anyway) it's best to use goto
.