Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration?

(在C#(随意回答其他语言)循环中,break和continue之间的区别是什么,作为离开循环结构的手段,并进入下一次迭代?)

Example:

(例:)

foreach (DataRow row in myTable.Rows)
{
    if (someConditionEvalsToTrue)
    {
        break; //what's the difference between this and continue ?
        //continue;
    }
}
  ask by Seibar translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
663 views
Welcome To Ask or Share your Answers For Others

1 Answer

break will exit the loop completely, continue will just skip the current iteration.

(break将完全退出循环, continue跳过当前迭代。)

For example:

(例如:)

for (int i = 0; i < 10; i++) {
    if (i == 0) {
        break;
    }

    DoSomeThingWith(i);
}

The break will cause the loop to exit on the first iteration - DoSomeThingWith will never be executed.

(中断将导致循环在第一次迭代时退出 - DoSomeThingWith永远不会被执行。)

This here:

(这里:)

for (int i = 0; i < 10; i++) {
    if(i == 0) {
        continue;
    }

    DoSomeThingWith(i);
}

Will not execute DoSomeThingWith for i = 0 , but the loop will continue and DoSomeThingWith will be executed for i = 1 to i = 9 .

(对于i = 0 ,不会执行DoSomeThingWith ,但循环将继续,并且对于i = 1i = 9将执行DoSomeThingWith 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...