本文介绍了如何使用break语句停止内部和外部循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有非常简单的代码,我在内循环中使用 break :

I have really simple code where I use break inside inner loop:

for (int it=0; it<5; it++) {
    for (int it2=0; it2<5; it2++) {
        if (it2==2)
            break; //break here not it2, but it loop
        NSLog(@"it=%d it2=%d", it, it2);
    }
}

我收到一个输出:

it=0 it2=0, it=0 it2=1,
it=1 it2=0, it=1 it2=1,
it=2 it2=0, it=2 it2=1,
it=3 it2=0, it=3 it2=1,
it=4 it2=0, it=4 it2=1

我知道在某些程序语言中有可能决定哪个循环语句应该影响。是否可以调用 break 停止外层循环( for with it variable)?

I know in some programic languages there is possibility to determine on which loop break statement should affect. Is it possible to call break to stop outer loop (for with it variable)?

推荐答案

如果你真的想这样做,那么咬一下子弹,使用 goto 。

If you really want to do this, then bite the bullet and use goto.

for (int it=0; it<5; it++) {
    for (int it2=0; it2<5; it2++) {
        if (it2==2)
            goto end_outer_loop;
        NSLog(@"it=%d it2=%d", it, it2);
    }
}

end_outer_loop:

// more stuff here.

这是合法的 goto 在向下方向)。事实上 break 是一种特殊的已批准goto,因为C是一个最小的语言,你必须在复杂的情况下使用显式的goto。

This is a legitimate goto (most gotos in the downward direction are). In fact break is a special kind of "approved" goto, and because C is a minimal language you have to use an explicit goto in complex cases.

,正如许多人在这里指出,它是更好的如果你可以使用 return。你的程序只是为了避免goto ,但在大多数情况下,它是一个线索,你的功能变得太复杂,因此应该分解。

However as many people here have pointed out, it's better if you can use return. You should not contort your program just to avoid goto, but in most cases it is a clue that your function is become too complex and should therefore be broken up.

这篇关于如何使用break语句停止内部和外部循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:23
查看更多