7

Is there a possibility for a continue or break to have a bigger scope than the currently running loop?
In the following example, I desire to to continue on the outer for-loop when expr is true, although it is called in the inner for-loop, so that neither [some inner code] nor [some outer code] is executed.

for(int outerCounter=0;outerCounter<20;outerCounter++){
   for(int innerCounter=0;innerCounter<20;innerCounter++){
      if(expr){
         [continue outer];    // here I wish to continue on the outer loop     
      }
      [some inner  code]
   }
   [some outer code]
}

In the above

HCL
  • 36,053
  • 27
  • 163
  • 213

4 Answers4

10

You can use goto if you absolutely must. However, I typically take one of two approaches:

  • Make the inner loop a separate method returning bool, so I can just return from it and indicate what the outer loop should do (break, continue, or do the rest of the loop body)
  • Keep a separate bool flag which is set before the inner loop, may be modified within the inner loop, and then is checked after the inner loop

Of these approaches I generally prefer the "extract method" approach.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    It is amazing how communication skills can make the difference sometimes. I actually prefer your answer over my own. – tzup Feb 14 '11 at 13:54
4

Do you mean something like this?

for(int outerCounter=0;outerCounter<20;outerCounter++){
   for(int innerCounter=0;innerCounter<20;innerCounter++){
      if(expr){
         runOuter = true;
         break; 
      }
      [some inner  code]
   }
   if (!runOuter) {
      [some outer code]
   }
   runOuter = false;
}
tzup
  • 3,566
  • 3
  • 26
  • 34
  • 1
    It won't since runOuter will be true and [some outer code] runs only if runOuter is false. Isn't this the logic you wanted? – tzup Feb 14 '11 at 13:50
  • +1 Yes thanks, this is the second version of Jon Skeets post. However my previous comment was related to your first answer which did not solve the problem. I have deleted my comment. – HCL Feb 14 '11 at 13:53
  • @HCL, I just realized that. It's weird you were able to see that post since I tried to quickly delete it when I realized my mistake and the post a better answer. Anyway, Jon fully deserves this answer. – tzup Feb 14 '11 at 13:58
1

You can use goto statement, otherwise - no, break and continue statements doesn't support this.

Although goto statement is considered as bad practice this is the only why to exit more than one for loops ... And it looks like this is the reason to be still a part of .NET

anthares
  • 11,070
  • 4
  • 41
  • 61
1

You can use goto statement with labels:

   for(int outerCounter=0;outerCounter<20;outerCounter++){
      for(int innerCounter=0;innerCounter<20;innerCounter++){
         if(expr){
            break; 
         }
         [some inner  code]
      }
      // You will come here after break
      [some outer code]
   }
whyleee
  • 4,019
  • 1
  • 31
  • 33