Continue and break up with extended reach

Is it possible for continue or break have more volume than the current loop?

In the following example, I want to continue the outer for loop when expr is true, although it is called in the inner for-loop, so neither [some inner code] nor [some outer code] are 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

+7
source share
4 answers

You can use goto if absolutely necessary. However, I usually take one of two approaches:

  • Make the inner loop a separate method returning bool , so I can just go back from it and specify what the outer loop should do (break, continue or execute the rest of the loop)
  • Keep a separate flag bool , which is set before the inner loop, can be changed in the inner loop, and then checked after the inner loop

Of these approaches, I usually prefer the โ€œextraction method" approach.

+11
source

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; } 
+4
source

You can use the goto statement; otherwise, the no, break, and continue statements do not support this.

Despite the fact that the goto statement is considered bad practice, this is the only reason to get out of a few loops ... And it seems that this is the reason to be still part of .NET.

+1
source

You can use the goto 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] } 
+1
source

All Articles