C# loop - break vs. continue *

Question

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?

Example:

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

Answer

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

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. 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.

< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/6414/" >C# loop - break vs. continue< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment