中断缩进循环结构
在诸如 for
之类的循环结构中,break;
是否“知道”何时处于缩进级别?
例如:
for (i = 0; i < 10; i++) {
for (s = 0; s <= i; s++) {
if (s == 7) break;
}
}
这个 break;
会同时停止还是仅停止内部?
谢谢
In a loop structure such as for
, does the break;
"know" when it's under indentation levels?
For example:
for (i = 0; i < 10; i++) {
for (s = 0; s <= i; s++) {
if (s == 7) break;
}
}
Will this break;
stop both for or just the inner one?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(6)
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
你还没有说你正在使用什么语言,但我从来没有见过一种具有这种语法的语言除了打破内部循环(允许外部循环继续)之外做任何事情。不过,您确实应该提及您正在使用的语言! :-)
许多具有此类语法的语言都支持标签和定向中断,可用于中断外循环。通常看起来像这样:(
在这种情况下
inner
标签是可选的,因为我们没有将它用于任何用途,我只是为了完整性而将其包含在内。)该示例将破坏内部 < em>和外循环。它在 Java、JavaScript 以及其他可能的语言中都有效;在 C 中,你需要在循环后面有一个标签,并且(不寒而栗)有一个
goto
,你可能会更好(可以说总是更好),只需在外循环中包含某种终止条件检查内循环是否设置。这是 JavaScript 中的一个实例(我使用了较小的数字以使其更加明显): 没有定向中断 | 使用定向中断。
另请注意,在这些语言中,缩进是完全无关的。此代码与您的代码完全相同(只是可读性明显较差):
这也是相同的(并且可读性明显较差):
显然您' d 永远不想这样做,但重点是缩进是为人而设计的,而不是编译器(在具有这种语法风格的语言中)。
You haven't said what language you're using, but I've never seen a language with that sort of syntax that did anything other than break the inner loop (allowing the outer to continue). Still, though, you really should mention what language you're using! :-)
Many of the languages with that sort of syntax support labels and directed breaks, which can be used to break the outer loop. That usually looks like this:
(The
inner
label is optional in this case because we haven't used it for anything, I've just included it for completeness.)That example would break both the inner and outer loops. It's valid in Java, JavaScript, and probably others; in C you'd need a label after the loop and (shudder) a
goto
and you'd probably be better off (arguably are always better off) just including some kind of termination condition in the outer loop's check that the inner loop sets.Here's a live example in JavaScript (I've used smaller numbers to make it more obvious): Without the directed break | With the directed break.
Also note that in these languages, indentation is completely irrelevant. This code is exactly the same your code (just markedly less readable):
This is also identical (and dramatically less readable):
Obviously you'd never want to do that, but the point is that indentation is for people, not compilers (in languages with this style of syntax).