Breaking nested loop and main loop [duplicate]

▼魔方 西西 提交于 2019-12-01 16:05:21

You can use a labeled break, which redirects the execution to after the block marked by the label:

OUTER:
while(x > 0) {
    for(int i = 5; i > 0; i++) {
        x = x-2;
        if(x == 0)
            break OUTER;
    }
}

Although in that specific case, a simple break would work because if x == 0 the while will exit too.

bool done=false;
while(!done && x > 0) {
    for(int i = 5;!done &&  i > 0 ; i++) {
        x = x-2;
        if(x == 0){
            done=true;
            break ;
        }
    }
}
cowls

See this example

Outer:
    for(int intOuter=0; intOuter < intArray.length ; intOuter++)
    {
      Inner:
      for(int intInner=0; intInner < intArray[intOuter].length; intInner++)
      {
        if(intArray[intOuter][intInner] == 30)
        {
          blnFound = true;
          break Outer;
        }  

      }
    }

Try to avoid breaks, there's always an other way to write your loop so you don't need it which is much 'prettier' and easier to understand if someone else has to modify your code. In your example the while loop is unnecessary but to show you how it's possible:

while(x > 0) {

  for(int i = 5; i > 0 && x!=0; i++) {

    x = x-2;

  }

}

If x equals 0, the for-loop will be left. Then your while condition will be verified: x is smaller then 0 (it's zero) so your while loop will stop executing too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!