tags:

views:

109

answers:

6

If you are in a 3rd nested loop in PHP, you can do break 3; and break all loops up 3 levels.

break seems to work in C. But if I do break 3 I get a syntax error. I guess it doesn't support it.

What is the best way to break multiple loops? Should I set a flag which is checked up the loops - and breaks if it is set?

Is there anything more elegant?

+9  A: 

You could use goto, but:

alt text

Daniel Vassallo
+10  A: 

Sometimes goto is the most elegant solution.

thyrgle
`goto LABEL;` is much more readable too.
John K
A: 

I also agree. goto has its uses and this is one of the main ones.

par
+6  A: 

The usual solutions are:

  • flags or other state checked in each of the nested loops
  • goto a label after the end of the outer loop
  • refactor your code so that the nested loops are in a function of their own. Use return to in effect break from the outermost loop.
Steve Jessop
+1 for more alternatives
alex
A: 

Steve Jessop's answer arrived a few seconds before I was ready to post my answer. I have one suggestion to add to his, although it may not be considered elegant - throw an exception.

GreenMatt
Does C have exceptions?
alex
@alex: <Sigh> Oh, this was C, wasn't it? Technically I guess it doesn't currently have exceptions, but C++ does. Google C and exceptions and you'll find some write ups on how to implement exceptions, e.g. this [Wikipedia write up](http://en.wikipedia.org/wiki/Exception_handling_syntax#C).
GreenMatt
Well, C may not have exceptions but C has `setjmp` and `longjmp`. Yep, you heard it here first. :-P (P.S. Any changes to your local variables might get undone, beware.)
Chris Jester-Young
@Chris: Wow, using `longjmp` to avoid a `goto` deserves some kind of award for Outstanding Dedication to Humorously Misunderstanding Dijkstra. Well done!
Steve Jessop
@Steve: Thanks, I aim to please! :-P +1
Chris Jester-Young
+3  A: 

Another way besides goto is to use a shared variable in all of the conditional portions of the for loops. This shared variable can be used like a kill switch for the loop.

bool done = false;
for (int i = 0; i < someNum && !done; i++ ) {
  for ( int j = 0; j < someOtherNum && !done; i++ ) {
    for ( int j = 0; j < again && !done; i++ ) { 
      if ( someCondition ) { 
        done = true;
        break;
      }
    }
  }
}
JaredPar