I came across this question a second ago, and I'm pulling some of the material off of there: Is there a name for the 'break n' construct?
This appears to be a needlessly complex way for people to have to instruct the program to break out of a double-nested for loop:
for (i = 0; i < 10; i++) {
bool broken = false;
for (j = 10; j > 0; j--) {
if (j == i) {
broken = true;
break;
}
}
if (broken)
break;
}
I know textbooks like to say goto statements are the devil, and I'm not fond of them at all myself, but does this justify an exception to the rule?
I'm looking for answers that deal with n-nested for loops.
NOTE: Whether you answer yes, no, or somewhere in between, completely close-minded answers are not welcome. Especially if the answer is no, then provide a good, legitimate reason why (which is not too far from Stack Exchange regulations anyway).
for (j = 10; j > 0 && !broken; j--)
then you wouldn't need thebreak;
statement. If you move the declaration ofbroken
to before the outer loop begins, then if that could be written asfor (i = 0; i < 10 && !broken; i++)
then I think nobreak;
s are necessary.goto
: goto (C# Reference) - "The goto statement is also useful to get out of deeply nested loops."goto
is actually required in a C# switch to fall-through to another case after executing any code inside the first case. That is the only case I have used goto, though.