Break statement inside two while loops

后端 未结 11 1168
时光取名叫无心
时光取名叫无心 2020-12-24 14:00

Let\'s say I have this:

while(a){

  while(b){

   if(b == 10)
     break;
 }
}

Question: Will the break statement take m

相关标签:
11条回答
  • 2020-12-24 14:51

    In your example break statement will take you out of while(b) loop

    while(a) {
    
       while(b) {
    
          if(b == 10) {
             break;
          }
       }  
       // break will take you here.
    }
    
    0 讨论(0)
  • 2020-12-24 14:54

    It will break out of the loop that immediately encloses it.

    You can however, break to a label:

    myLabel:
    
    while(a) {    
        while(b) {    
            if(b == 10)
                break myLabel;
        }
    }
    

    I don't generally like to use this pattern because it easily leads to spaghetti code. Use an unlabeled break or a flag to terminate your loop.

    0 讨论(0)
  • 2020-12-24 14:58

    A break statement will take you out of the innermost loop enclosing that break statement.

    In the example the inner while loop.

    0 讨论(0)
  • 2020-12-24 14:59

    @Abhishekkumar

    Break keyword has it's derived root from C and Assembly, and Break it's sole purpose to passes control out of the compound statement i.e. Loop, Condition, Method or Procedures.

    Please refer these...

    http://tigcc.ticalc.org/doc/keywords.html#break

    http://www.functionx.com/cpp/keywords/break.htm

    http://en.wikipedia.org/wiki/Break_statement#Early_exit_from_loops

    So, if you want to get out of Two loops at same time then you've to use two Breaks, i.e. one in inner loop and one in outer loop.

    But you want to stop both loop at same time then you must have to use exit or return.

    0 讨论(0)
  • 2020-12-24 15:01

    You can raise a flag to pass the information to the outer while loop. In this case the information can be stored in a variable breakOuterLoopFlag and the outer while loop acts according to this information. See pseudo code below:

    int breakOuterLoopFlag = 0;
    
    while(a){
       
      while(b){
          if(b == 10) {
            breakOuterLoopFlag = 1;
            break;
          }
        }
    
       if(breakOuterLoopFlag == 1) {
         break;
       }
    }
    
    0 讨论(0)
提交回复
热议问题