是否可以使用break函数退出几个嵌套的for循环?

如果是,你会怎么做呢?你还能控制刹车出多少圈吗?


当前回答

Breaking out of a for-loop is a little strange to me, since the semantics of a for-loop typically indicate that it will execute a specified number of times. However, it's not bad in all cases; if you're searching for something in a collection and want to break after you find it, it's useful. Breaking out of nested loops, however, isn't possible in C++; it is in other languages through the use of a labeled break. You can use a label and a goto, but that might give you heartburn at night..? Seems like the best option though.

其他回答

Breaking out of a for-loop is a little strange to me, since the semantics of a for-loop typically indicate that it will execute a specified number of times. However, it's not bad in all cases; if you're searching for something in a collection and want to break after you find it, it's useful. Breaking out of nested loops, however, isn't possible in C++; it is in other languages through the use of a labeled break. You can use a label and a goto, but that might give you heartburn at night..? Seems like the best option though.

只是使用lambdas添加一个显式的答案:

  for (int i = 0; i < n1; ++i) {
    [&] {
      for (int j = 0; j < n2; ++j) {
        for (int k = 0; k < n3; ++k) {
          return; // yay we're breaking out of 2 loops here
        }
      }
    }();
  }

当然,这种模式有一定的局限性,显然只适用于c++ 11,但我认为它非常有用。

break语句终止它出现的最近的封闭do、for、switch或while语句的执行。控制权转移到终止语句后面的语句。

从msdn。

Break将只退出包含它的最内层循环。

你可以使用goto来跳出任意数量的循环。

当然,goto通常被认为是有害的。

使用break函数[…]是否合适?

使用break和goto会使判断程序的正确性变得更加困难。请看这里关于这个问题的讨论:Dijkstra不是疯子。

虽然这个答案已经提出了,但我认为一个很好的方法是这样做:

for(unsigned int z = 0; z < z_max; z++)
{
    bool gotoMainLoop = false;
    for(unsigned int y = 0; y < y_max && !gotoMainLoop; y++)
    {
        for(unsigned int x = 0; x < x_max && !gotoMainLoop; x++)
        {
                          //do your stuff
                          if(condition)
                            gotoMainLoop = true;
        }
    }

}