如何在另一个循环中打破循环

时间:2013-03-02 22:22:34

标签: c loops break

如果彼此内部有3个循环我怎么能打破上层循环我的意思是:

while (abc) {
    for (int dep =0 ; dep<b ; dep++)  {
         for (int jwe=0 ; jwe<g ; jwe++) {
             if (! (ef || hf) ) {
             //here is where i want to break to loop while
             //or in other purpose (other situation) i need 
             //to know how i could break to first loop  
             //i mean (for (int dep =0 ; dep< b ; dep++)
             }
         }
    }
} 

有人请帮助我,如果之后,我可以打破到while循环,或者我如何打破第一个循环“for”。

6 个答案:

答案 0 :(得分:4)

只需将外循环的计数器设置为一个不会再次运行的值。

while (abc) {
    for (int dep =0 ; dep<b ; dep++)
    for (int jwe=0 ; jwe<g ; jwe++)
     if (! (ef || hf) ) {
         //here is where you want to break to the while-loop
         //abc = 0; here will make it exit the entire while as well
         dep = b; //in order to exit the first for-loop
         break;
     }
} 

答案 1 :(得分:2)

这是(罕见)goto是最清晰的构造的情况之一:

while (abc) {
    for (int dep =0 ; dep<b ; dep++)  {
         for (int jwe=0 ; jwe<g ; jwe++) {
             if (! (ef || hf) ) {
                 // Do anything needed before leaving "in the middle"
                 goto out;
             }
         }
    }
}
out:
// Continue here

确保缩进不会隐藏标签。

答案 2 :(得分:0)

某些语言(包括Java)支持打破标签:

outerLoop: // a label
while(true) {
   for(int i = 0; i < X; i++) {
      for(int j = 0; j < Y; j++) {
         // do stuff 
         break outerLoop; // go to your label
      }
   }
}

答案 3 :(得分:0)

int breakForLoop=0;
    int breakWhileLoop=0;
    while (abc) {

        for (int dep = 0;dep < b;dep++) {

            for (int jwe = 0;jwe < g; jwe++) {


                if (!(ef || hf)) {
                    breakForLoop=1;
                    breakWhileLoop=1;
                    break;

                }
            }
            if(breakForLoop==1){
                break;
            }
        }
        if( breakWhileLoop==1){
                break;
            }
    } 

答案 4 :(得分:0)

例如,使用int变量int terminate = 0;,并将其与条件while(true && terminate == 0)一起放入while循环中。如果要打破外部循环,请在从内部循环中断之前将变量设置为1

答案 5 :(得分:0)

continue_outer_loop = true;
while (abc) {

  for ( int i = 0; i < X && continue_outer_loop; i++) {
    for ( int j = 0; j < Y; j++ {

       if (defg) {
         continue_outer_loop = false;  // exit outer for loop
         break;                        // exit inner for loop
       }

    }
  }
}