Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

continue and break with an extended scope

Tags:

c#

.net

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

like image 411
HCL Avatar asked Feb 14 '11 13:02

HCL


4 Answers

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.

like image 97
Jon Skeet Avatar answered Nov 18 '22 19:11

Jon Skeet


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;
}
like image 29
tzup Avatar answered Nov 18 '22 20:11

tzup


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

like image 38
anthares Avatar answered Nov 18 '22 20:11

anthares


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]
   }
like image 41
whyleee Avatar answered Nov 18 '22 20:11

whyleee