0

みたいなループで、

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

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

    footwo();
}

ループの特定のターンを返すにはどうすればよいですか?

という条件で footwo() を実行できることは知っていますi >= 5が、ループを終了させる方法があるかどうか疑問に思っています (一度だけ)。

詳細については、ループiの特定の「ループ」がちょうど終了したかのように、 for ループを最初から開始し、 に 1 を追加したいと思います。

(奇妙な言い回しに基づいてこれに対する答えを見つけることができませんでしたが、もしあれば、私に指示してください。喜んでこれを削除します。)

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 に答える
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 に答える