从没有goto的嵌套循环退出

时间:2015-11-29 10:40:32

标签: c++

如何在没有goto的情况下退出嵌套的while()或for()?

例如,如果我在函数中使用如下所示的三个循环:

   void myfun(){
    for (;;)
    {
        while( true )
        {
            for (;;)
            {

          //what is the exit code of all loop()  from here?
            }
        }
     }
    }

使用break;只能退出一个循环,
但是我如何退出所有循环呢? 循环可以通过计数器限制或无限制。

3 个答案:

答案 0 :(得分:3)

我个人会重写代码,以便您首先没有嵌套循环。像这样:

bool myFun2
{
    for (;;)
    {
        if(something) return true;
    }
    // If the loop isn't "forever", return false here?
}


bool myFun1()
{
    while( true )
    {
       if (myFun2()) return true;
    }
    // return false here if needed.
}

void myfun()
{
   for (;;)
   { 
      if(myFun1()) break;
   }
}

例如,这比试图确定某些exitLoop变量设置的条件要容易得多。

答案 1 :(得分:1)

您无法在while上下文中进行另一次中断或更改您的循环,将变量作为退出标记:

      bool exit = false;
      for (;;){
       while (!exit){
            for (;;){
               exit = true; 
               break;
            }
       }
       if (exit) break;
      }

您的代码中有多少循环

答案 2 :(得分:0)

如果您想跳出离开该功能的function,那么您应该使用return。但是,如果你想跳出嵌套循环&没有超出功能,你可以throw an exception。这种方法可以帮助您将代码分解为多个functions。但exceptions适用于图书馆设计师和我们应该避免使用它们太多。就个人而言,在这种情况下使用goto是最好的事情,但是当你提出反对意见时,我就是这样说的。那么你的代码将如下所示: -

void myfun()
{
    try
    {
        for (;;)
    {
        while( true )
        {
            for (;;)
            {
                if (/*some condition*/)
                throw false;
            }
        }
    }
    }
    catch (bool)
    {
        cout<<"caught";
    }
    // do stuffs if your code is successful that is you don't break out
}
相关问题