你能像 PHP 那样通过传递数字来“中断”多个循环吗?

发布于 2024-09-30 05:08:36 字数 226 浏览 0 评论 0原文

如果您处于 PHP 中的第三个嵌套循环中,则可以执行 break 3; 并将所有循环分解为 3 层。

break 似乎可以在 C 中工作。但是如果我执行 break 3 ,则会出现语法错误。估计是不支持吧

打破多个循环的最佳方法是什么?我是否应该设置一个标志来检查循环 - 如果设置了则中断?

还有更优雅的吗?

If you are in a 3rd nested loop in PHP, you can do break 3; and break all loops up 3 levels.

break seems to work in C. But if I do break 3 I get a syntax error. I guess it doesn't support it.

What is the best way to break multiple loops? Should I set a flag which is checked up the loops - and breaks if it is set?

Is there anything more elegant?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

り繁华旳梦境 2024-10-07 05:08:36

有时 goto 是最优雅的解决方案。

Sometimes goto is the most elegant solution.

樱花落人离去 2024-10-07 05:08:36

您可以使用 goto,但是:

alt text

You could use goto, but:

alt text

你的往事 2024-10-07 05:08:36

通常的解决方案是:

  • 在每个嵌套循环中检查标志或其他状态
  • 在外部循环结束后goto
  • 重构代码,以便嵌套循环处于其自己的函数中。使用 return 实际上可以从最外层循环中中断。

The usual solutions are:

  • flags or other state checked in each of the nested loops
  • goto a label after the end of the outer loop
  • refactor your code so that the nested loops are in a function of their own. Use return to in effect break from the outermost loop.
花开浅夏 2024-10-07 05:08:36

除了 goto 之外的另一种方法是在 for 循环的所有条件部分中使用共享变量。这个共享变量可以像循环的终止开关一样使用。

bool done = false;
for (int i = 0; i < someNum && !done; i++ ) {
  for ( int j = 0; j < someOtherNum && !done; i++ ) {
    for ( int j = 0; j < again && !done; i++ ) { 
      if ( someCondition ) { 
        done = true;
        break;
      }
    }
  }
}

Another way besides goto is to use a shared variable in all of the conditional portions of the for loops. This shared variable can be used like a kill switch for the loop.

bool done = false;
for (int i = 0; i < someNum && !done; i++ ) {
  for ( int j = 0; j < someOtherNum && !done; i++ ) {
    for ( int j = 0; j < again && !done; i++ ) { 
      if ( someCondition ) { 
        done = true;
        break;
      }
    }
  }
}
阪姬 2024-10-07 05:08:36

我也同意。 goto 有其用途,这是主要用途之一。

I also agree. goto has its uses and this is one of the main ones.

美羊羊 2024-10-07 05:08:36

在我准备发布我的答案之前几秒钟,史蒂夫·杰索普就给出了答案。我有一个建议要添加到他的建议中,尽管它可能不被认为是优雅的 - 抛出异常。

Steve Jessop's answer arrived a few seconds before I was ready to post my answer. I have one suggestion to add to his, although it may not be considered elegant - throw an exception.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文