0

在这样的循环中,

for (int i = 0; i < 5; i++)
{
    int i_foo;

    i_foo = foo();
    if (i < 5)
        return; //<-------- Right here

    footwo();
}

我将如何返回一个特定的循环?

我知道我可以让 footwo() 在条件下执行i >= 5,但我想知道是否有办法让循环退出(只是一次)。

为了获得更多解释,我希望 for 循环从头开始并添加 1 i,就好像它刚刚完成了循环的那个特定“循环”。

(根据奇怪的措辞我找不到答案,但如果有一个直接告诉我,我会很高兴地把它记下来。)

4

4 回答 4

8

使用continue

if (i < 5)
    continue;

这会直接跳到循环的下一次迭代。

于 2013-07-24T19:08:46.940 回答
2

我不完全是你所说的,但为了澄清一些术语,我认为当你说“循环的转折”或“循环的循环”时,你的意思是说“迭代”。通用术语允许更好的清晰度。

至于你的问题:

如果您使用continue关键字,它允许您跳到下一个迭代。如果使用break关键字,它将跳过整个迭代结构(完全跳出 for 循环)。这也适用于while语句。

于 2013-07-24T19:11:24.637 回答
2

我不完全确定您的意思,但如果您正在检查条件,if (i < 5)那么只需使用关键字continue。如果表达式为真,则循环将continue.

于 2013-07-24T19:09:33.750 回答
1

You can use continue to terminate the current iteration of a loop without terminating the loop itself. But depending on how your code is structured, an if statement might be cleaner.

Given your example, you might want:

for (int i = 0; i < 5; i++)
{
    int i_foo;

    i_foo = foo();
    if (i_foo >= 5) {
        footwo();
    }
}

I'm assuming that you meant to assign the result of foo() to i_foo, not to i.

A continue can be simpler if you need to bail out from the middle of some nested structure, or if you need to bail out very early in the body of the loop and there's a lot of code that would be shoved into the if.

But in the case of nested control structures, you need to remember that continue applies only to the innermost enclosing loop; there's no construct (other than goto) for bailing out of multiple nested loops. And break applies to the innermost enclosing loop or switch statement.

于 2013-07-24T19:14:16.443 回答