打破for循环 [英] break out of for loop

查看:73
本文介绍了打破for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我知道我必须使用break才能退出for循环.
但是,如果彼此之间有多个循环,那么如何退出所有循环?
您必须在每个for循环的末尾使用break还是我可以只使用一个break退出所有循环?


Hi,
I know I have to use break to exit from a for loop.
But if you have several loops within eachother then how do you exit all of the loops?
Do you have to use break at the end of each for loop or can I just use one break to exit all loops?

i.e.

for (condition)
{
 for(condition)
 {
  for(condition)
  {
   if (myBoolean == false)
    {
     break;
    }
  }
 } 
}

推荐答案

这取决于您是否总是打破所有循环的逻辑,但是您将需要实现一些逻辑以打破循环.
根据您的逻辑,您可能需要多个变量,但这显示了基本原理

It will depend on your logic of whether you would always break out all the loops, but you are going to need to implement some logic to break out of the loops.
You may need more than one variable depending on your logic, but this shows the basic principle

bool breakAll = false;
for (condition1)
{
    for(condition2)
    {
        for(condition3)
        {
            if (myBoolean == false)
            {
                breakAll = true;
                break; // breaks condition3 for loop
            }
        }
        if (breakAll)
        {
            break; // breaks condition2 for loop
        }
    }

    if (breakAll)
    {
        break; // breaks condition1 for loop
    }
}


break statemnet只会从 current 循环中退出-没有机制可以从所有循环中退出.我可能会将它们编码为一个方法,并改为使用return.有些纯粹主义者会告诉我们,多个出口点是撒但的产物.
如果您不能使用return,那么这是可以证明goto合理的少数情况之一.
A break statemnet will only exit from the current loop - there is no mechanism to exit from all loops. I would probably code them into a method, and use a return instead. There are purists who will tell that multiple exit points are the spawn of Satan however.
If you can''t use return than this is one of the very, very few occaisions when a goto can be justified.


您不能使用break离开嵌套循环.

您可以使用goto或将代码放入函数中,然后使用return删除该代码.
You cannot use break to get out of nested loops.

You could either use a goto or place the code in a function and use a return to get out of it.


这篇关于打破for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆