在没有goto的情况下退出嵌套循环

exiting from nested loop without goto

本文关键字:情况下 退出 嵌套循环 goto      更新时间:2023-10-16

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

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

   void myfun(){
    for (;;)
    {
        while( true )
        {
            for (;;)
            {
          //what is the exit code of all loop()  from here?
            }
        }
     }
    }

使用break;只能退出一个循环,
但是我怎样才能退出所有循环呢
循环可以由计数器限制或不受限制。

我个人会重写代码,这样一来就不会有嵌套循环。类似这样的东西:

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变量设置的条件要容易得多。

不能,您需要在while上下文中再次中断,或者使用变量作为退出标志来更改循环:

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

你的代码中有多少循环就有多少循环

如果您想跳出离开函数的function,那么您应该使用return。然而,如果你只想跳出嵌套的循环&不出功能,则可以throw an exception。这种方法将帮助您避免像一些人所做的那样将代码分解为几个functions。然而CCD_ 8是为图书馆设计者设计的;我们应该避免过度使用它们。就我个人而言,使用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
}