你能像 PHP 那样通过传递数字来“中断”多个循环吗?
如果您处于 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有时 goto 是最优雅的解决方案。
Sometimes goto is the most elegant solution.
您可以使用
goto
,但是:You could use
goto
, but:通常的解决方案是:
goto
return
实际上可以从最外层循环中中断。The usual solutions are:
goto
a label after the end of the outer loopreturn
to in effect break from the outermost loop.除了 goto 之外的另一种方法是在 for 循环的所有条件部分中使用共享变量。这个共享变量可以像循环的终止开关一样使用。
Another way besides
goto
is to use a shared variable in all of the conditional portions of thefor
loops. This shared variable can be used like a kill switch for the loop.我也同意。 goto 有其用途,这是主要用途之一。
I also agree. goto has its uses and this is one of the main ones.
在我准备发布我的答案之前几秒钟,史蒂夫·杰索普就给出了答案。我有一个建议要添加到他的建议中,尽管它可能不被认为是优雅的 - 抛出异常。
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.