开发者

Can you `break` from multiple loops like PHP can by passing a number?

If you are in a 3rd nested loop in PHP, you can do break 3; and 开发者_JS百科break all loops up 3 levels.

break seems to work in C. But if I do break 3 I get a syntax error. I guess it doesn't support it.

What is the best way to break multiple loops? Should I set a flag which is checked up the loops - and breaks if it is set?

Is there anything more elegant?


Sometimes goto is the most elegant solution.


You could use goto, but:

Can you `break` from multiple loops like PHP can by passing a number?


The usual solutions are:

  • flags or other state checked in each of the nested loops
  • goto a label after the end of the outer loop
  • refactor your code so that the nested loops are in a function of their own. Use return to in effect break from the outermost loop.


Another way besides goto is to use a shared variable in all of the conditional portions of the for loops. This shared variable can be used like a kill switch for the loop.

bool done = false;
for (int i = 0; i < someNum && !done; i++ ) {
  for ( int j = 0; j < someOtherNum && !done; i++ ) {
    for ( int j = 0; j < again && !done; i++ ) { 
      if ( someCondition ) { 
        done = true;
        break;
      }
    }
  }
}


I also agree. goto has its uses and this is one of the main ones.


Steve Jessop's answer arrived a few seconds before I was ready to post my answer. I have one suggestion to add to his, although it may not be considered elegant - throw an exception.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜