HiveBrain v1.2.0
Get Started
← Back to all entries
principlecsharpCritical

C# loop — break vs. continue

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
loopbreakcontinue

Problem

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;
    }
}

Solution

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.

While:

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

    DoSomeThingWith(i);
}


Here continue skips to the next iteration of the for-loop, meaning DoSomeThingWith will not execute for i == 0.

But the loop will continue and DoSomeThingWith will be executed for i == 1 to i == 9.

Code Snippets

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

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

    DoSomeThingWith(i);
}

Context

Stack Overflow Q#6414, score: 1636

Revisions (0)

No revisions yet.