0

Does the keyword 'break' only jump out of one layer of loop? In this piece of code, there are 3 layers loops, which I want to jump out completely. Is there an easy to do that?

while(){

   while(){

       for(){
         if(a==b){
           // I want to jump out of the outer while() loop. 
         }
         }
    }
}
// and the logic continues from this line.
marlon
  • 6,029
  • 8
  • 42
  • 76
  • i usually find if you need to do something like that, it warrants splitting the code out into different methods which can return before the end of the method block. any convoluted flow control usually hints there is a more structured solution possible. – slipperyseal Sep 22 '17 at 01:03
  • You mean for example I can add two methods, which can return from the 'for' loop and the inner "while" loop? – marlon Sep 22 '17 at 01:10
  • i cant comment on your example because the while and for loops have no conditions, so im not sure how id restructure any given code. but in all my (horribly long) years of developing i'v never needed to use nested breaks – slipperyseal Sep 22 '17 at 01:16
  • its a bit like the argument against goto statements. people say sometimes there's a need. you can almost always find a clean solution which avoids them – slipperyseal Sep 22 '17 at 01:17
  • actually, i can think of a solution for the above. move the whole thing into a method, then rather than trying to break to the end, simply return. this a common pattern in search functions which have lots of nested loops, but when it finds something it returns the found value from down within the loops. if it reached the end, then it has found nothing and can return null or throw an exception – slipperyseal Sep 22 '17 at 01:19

0 Answers0