818

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;
    }
}
callisto
  • 4,641
  • 9
  • 48
  • 86
Seibar
  • 63,705
  • 37
  • 85
  • 98
  • 2
    blog post with culmination of below http://www.adamthings.com/post/2012/07/26/ensure-threads-have-finished-before-method-continues-in-c-using-thread-join/ – Adam Jun 19 '13 at 22:05
  • 9
    `continue;` will stop processing of the current `row` and continue with the _next_ `row` from the collection. On the other hand, `break;` will leave the `foreach` statement completely and the remaining rows will never be processed. – Jeppe Stig Nielsen Dec 29 '17 at 14:01
  • Possible duplicate of [C# go to next item in list based on if statement in foreach](https://stackoverflow.com/questions/4266456/c-sharp-go-to-next-item-in-list-based-on-if-statement-in-foreach) – Erik Silva Aug 27 '19 at 18:56

15 Answers15

1539

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.

Michael Stum
  • 167,397
  • 108
  • 388
  • 523
  • 2
    Why are their no braces around continue - I know that it works without them, but why? – George Willcox Jul 08 '16 at 16:06
  • 57
    @GeorgeWillcox My younger, more foolish self hadn't yet learned the value of using braces, always. (They are optional in C# for single statements, but not putting them makes it easier to introduce a bug later on. Also see http://programmers.stackexchange.com/a/16530/6342) – Michael Stum Jul 08 '16 at 17:20
388

A really easy way to understand this is to place the word "loop" after each of the keywords. The terms now make sense if they are just read like everyday phrases.

break loop - looping is broken and stops.

continue loop - loop continues to execute with the next iteration.

Raktim Biswas
  • 3,833
  • 5
  • 22
  • 29
JeremiahClark
  • 5,151
  • 2
  • 17
  • 14
106

break causes the program counter to jump out of the scope of the innermost loop

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

Works like this

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto BREAK;
}
BREAK:;

continue jumps to the end of the loop. In a for loop, continue jumps to the increment expression.

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

    printf("%d", i);
}

Works like this

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto CONTINUE;

    printf("%d", i);

    CONTINUE:;
}
SemiColon
  • 2,097
  • 2
  • 14
  • 13
  • 2
    I notice that many loops here just use the standard `for` loop, but will this work for pre and post tested `while` loops? The `goto` notation leads me to believe so, but need some verification. – Daniel Park Aug 08 '13 at 03:02
  • 1
    @Daniel, for WHILE loops you can use BREAK and CONTINUE, no problem. – Amila Apr 21 '15 at 05:09
  • @DanielPark For both `while` ("pre-tested") and `do`-`while` ("post-tested"), after a `continue;` statement is met the next thing that will happen is that the loop condition is evaluated to decide whether an additional iteration is to be done. Of course, with `break;` the loop condition is _not_ checked, the loop is simply exited completely. So the `goto` analogy is good for understanding this aspect too. – Jeppe Stig Nielsen Dec 29 '17 at 14:16
41

I used to always get confused whether I should use break, or continue. This is what helps me remember:

When to use break vs continue?

  1. Break - it's like breaking up. It's sad, you guys are parting. The loop is exited.

Break

  1. Continue - means that you're gonna give today a rest and sort it all out tomorrow (i.e. skip the current iteration)!

Continue

BKSpurgeon
  • 24,945
  • 9
  • 86
  • 68
  • Will share this with my partner. May be Continue should be renamed to GetOverIt, and Break should be renamed to MoveOnForward. No wonder we are called geeks, how does Break make any sense? It sounds destructive. And one that needs to be added is - STOP, or even better EndIt - will fix many bugs, and make C-sharp truly sharp. – Mike Mar 05 '20 at 11:29
  • Into the flood again Same old trip it was back then So I made a big mistake Try to see it once my way – Talal Zahid Apr 02 '20 at 23:48
  • @TalalZahid i do not understand? – BKSpurgeon Apr 03 '20 at 01:53
30

break would stop the foreach loop completely, continue would skip to the next DataRow.

Raktim Biswas
  • 3,833
  • 5
  • 22
  • 29
palmsey
  • 5,654
  • 3
  • 31
  • 40
20

There are more than a few people who don't like break and continue. The latest complaint I saw about them was in JavaScript: The Good Parts by Douglas Crockford. But I find that sometimes using one of them really simplifies things, especially if your language doesn't include a do-while or do-until style of loop.

I tend to use break in loops that are searching a list for something. Once found, there's no point in continuing, so you might as well quit.

I use continue when doing something with most elements of a list, but still want to skip over a few.

The break statement also comes in handy when polling for a valid response from somebody or something. Instead of:

Ask a question
While the answer is invalid:
    Ask the question

You could eliminate some duplication and use:

While True:
    Ask a question
    If the answer is valid:
        break

The do-until loop that I mentioned before is the more elegant solution for that particular problem:

Do:
    Ask a question
    Until the answer is valid

No duplication, and no break needed either.

yukondude
  • 22,441
  • 13
  • 45
  • 56
13

All have given a very good explanation. I am still posting my answer just to give an example if that can help.

// break statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break; // It will force to come out from the loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

0[Printed] 1[Printed] 2[Printed]

So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3

//continue statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        continue; // It will take the control to start point of loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

0[Printed] 1[Printed] 2[Printed] 4[Printed]

So 3[Printed] will not be displayed as there is continue when i == 3

Paul Zahra
  • 8,906
  • 7
  • 49
  • 65
Pritom Nandy
  • 1,185
  • 9
  • 5
7

Break

Break forces a loop to exit immediately.

Continue

This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code.

Sona Rijesh
  • 926
  • 5
  • 26
  • 55
6

By example

foreach(var i in Enumerable.Range(1,3))
{
    Console.WriteLine(i);
}

Prints 1, 2, 3 (on separate lines).

Add a break condition at i = 2

foreach(var i in Enumerable.Range(1,3))
{
    if (i == 2)
        break;

    Console.WriteLine(i);
}

Now the loop prints 1 and stops.

Replace the break with a continue.

foreach(var i in Enumerable.Range(1,3))
{
    if (i == 2)
        continue;

    Console.WriteLine(i);
}

Now to loop prints 1 and 3 (skipping 2).

Thus, break stops the loop, whereas continue skips to the next iteration.

Markus Safar
  • 5,899
  • 5
  • 25
  • 41
Colonel Panic
  • 119,181
  • 74
  • 363
  • 435
6

Simple answer:

Break exits the loop immediately.
Continue starts processing the next item. (If there are any, by jumping to the evaluating line of the for/while)

Maltrap
  • 2,612
  • 1
  • 32
  • 32
5

Ruby unfortunately is a bit different. PS: My memory is a bit hazy on this so apologies if I'm wrong

instead of break/continue, it has break/next, which behave the same in terms of loops

Loops (like everything else) are expressions, and "return" the last thing that they did. Most of the time, getting the return value from a loop is pointless, so everyone just does this

a = 5
while a < 10
    a + 1
end

You can however do this

a = 5
b = while a < 10
    a + 1
end # b is now 10

HOWEVER, a lot of ruby code 'emulates' a loop by using a block. The canonical example is

10.times do |x|
    puts x
end

As it is much more common for people to want to do things with the result of a block, this is where it gets messy. break/next mean different things in the context of a block.

break will jump out of the code that called the block

next will skip the rest of the code in the block, and 'return' what you specify to the caller of the block. This doesn't make any sense without examples.

def timesten
    10.times{ |t| puts yield t }
end


timesten do |x|
   x * 2
end
# will print
2
4
6
8 ... and so on


timesten do |x|
    break
    x * 2
end
# won't print anything. The break jumps out of the timesten function entirely, and the call to `puts` inside it gets skipped

timesten do |x|
    break 5
    x * 2
end
# This is the same as above. it's "returning" 5, but nobody is catching it. If you did a = timesten... then a would get assigned to 5

timesten do |x|
    next 5
    x * 2
end 
# this would print
5
5
5 ... and so on, because 'next 5' skips the 'x * 2' and 'returns' 5.

So yeah. Ruby is awesome, but it has some awful corner-cases. This is the second worst one I've seen in my years of using it :-)

Orion Edwards
  • 113,829
  • 60
  • 223
  • 307
5

Please let me state the obvious: note that adding neither break nor continue, will resume your program; i.e. I trapped for a certain error, then after logging it, I wanted to resume processing, and there were more code tasks in between the next row, so I just let it fall through.

David Hall
  • 30,887
  • 10
  • 88
  • 121
3

To break completely out of a foreach loop, break is used;

To go to the next iteration in the loop, continue is used;

Break is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.

Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.

Gopesh Sharma
  • 5,725
  • 4
  • 23
  • 34
2

if you don't want to use break you just increase value of I in such a way that it make iteration condition false and loop will not execute on next iteration.

for(int i = 0; i < list.Count; i++){
   if(i == 5)
    i = list.Count;  //it will make "i<list.Count" false and loop will exit
}
Umair Khalid
  • 1,961
  • 1
  • 18
  • 25
  • While this works, it's not a good approach. The keyword `break` signifies your intent. If I saw that, I would be wondering what's going on... It would take a few extra ticks for me to figure out why someone is doing that. `break` exists for this purpose, and it's silly to do something more confusing just to avoid using a keyword. – Mike Christiansen Jan 16 '21 at 14:32
0

As for other languages:

'VB
For i=0 To 10
   If i=5 then Exit For '= break in C#;
   'Do Something for i<5
next

For i=0 To 10
   If i=5 then Continue For '= continue in C#
   'Do Something for i<>5...
Next
dba
  • 712
  • 1
  • 11
  • 20