C# loop — break vs. continue
Asked Answered
N

16

878

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;
    }
}
Napolitano answered 8/8, 2008 at 21:49 Comment(3)
blog post with culmination of below adamthings.com/post/2012/07/26/…Dyewood
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.Palmy
Possible duplicate of C# go to next item in list based on if statement in foreachMontane
A
1614

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.

Anthocyanin answered 8/8, 2008 at 21:51 Comment(2)
Why are their no braces around continue - I know that it works without them, but why?Stratovision
@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 programmers.stackexchange.com/a/16530/6342)Anthocyanin
M
404

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.

Munt answered 8/8, 2008 at 22:33 Comment(0)
B
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:;
}
Besmirch answered 19/8, 2008 at 20:21 Comment(3)
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.Trocar
@Daniel, for WHILE loops you can use BREAK and CONTINUE, no problem.Elastance
@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.Palmy
N
65

When to use break vs continue?

  1. Break - We're leaving the loop forever and breaking up forever. Good bye.

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

(Corny stories ¯¯\(ツ)/¯¯ and pics solely to help you remember...hopefully you'll never forget)

Gripe Alert:

No idea why those words are being used. If you want to skip the iteration, why not use the word skip instead of continue? This entire Stack overflow question and 1000s of developers would not be confused if the proper name was given.)

Nilotic answered 5/12, 2017 at 23:7 Comment(2)
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.Unbodied
Into the flood again Same old trip it was back then So I made a big mistake Try to see it once my wayAficionado
F
30

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

Floodlight answered 8/8, 2008 at 21:50 Comment(0)
P
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.

Pistoia answered 8/8, 2008 at 22:35 Comment(0)
F
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

Farad answered 21/12, 2010 at 7:27 Comment(0)
C
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.

Celik answered 28/3, 2013 at 6:58 Comment(2)
Continue checks the loop condition too :)Jotunheim
Continue is not the opposite of break, break stops the loop, continue stops the current iteration.Claudication
M
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)

Metchnikoff answered 22/10, 2008 at 9:11 Comment(0)
L
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.

Leggy answered 10/10, 2013 at 15:34 Comment(0)
L
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 :-)

Logicize answered 9/8, 2008 at 2:31 Comment(0)
H
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.

Hoarfrost answered 23/3, 2009 at 18:23 Comment(0)
T
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.

Toponym answered 9/3, 2013 at 12:50 Comment(0)
H
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
}
Heterochromous answered 3/2, 2016 at 6:18 Comment(1)
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.Outturn
S
1

Since the example written here are pretty simple for understanding the concept I think it's also a good idea to look at the more practical version of the continue statement being used. For example:

we ask the user to enter 5 unique numbers if the number is already entered we give them an error and we continue our program.

static void Main(string[] args)
        {
            var numbers = new List<int>();


            while (numbers.Count < 5)
            { 
            
                Console.WriteLine("Enter 5 uniqe numbers:");
                var number = Convert.ToInt32(Console.ReadLine());



                if (numbers.Contains(number))
                {
                    Console.WriteLine("You have already entered" + number);
                    continue;
                }



                numbers.Add(number);
            }


            numbers.Sort();


            foreach(var number in numbers)
            {
                Console.WriteLine(number);
            }


        }

lets say the users input were 1,2,2,2,3,4,5.the result printed would be:

1,2,3,4,5

Why? because every time user entered a number that was already on the list, our program ignored it and didn't add what's already on the list to it. Now if we try the same code but without continue statement and let's say with the same input from the user which was 1,2,2,2,3,4,5. the output would be :

1,2,2,2,3,4

Why? because there was no continue statement to let our program know it should ignore the already entered number.

Now for the Break statement, again I think its the best to show by example. For example:

Here we want our program to continuously ask the user to enter a number. We want the loop to terminate when the user types “ok" and at the end Calculate the sum of all the previously entered numbers and display it on the console.

This is how the break statement is used in this example:

{
            var sum = 0;
            while (true)
            {
                Console.Write("Enter a number (or 'ok' to exit): ");
                var input = Console.ReadLine();

                if (input.ToLower() == "ok")
                    break;

                sum += Convert.ToInt32(input);
            }
            Console.WriteLine("Sum of all numbers is: " + sum);
        }

The program will ask the user to enter a number till the user types "OK" and only after that, the result would be shown. Why? because break statement finished or stops the ongoing process when it has reached the condition needed.

if there was no break statement there, the program would keep running and nothing would happen when the user typed "ok".

I recommend copying this code and trying to remove or add these statements and see the changes yourself.

Sorrow answered 11/9, 2021 at 21:37 Comment(0)
T
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
Twiddle answered 20/2, 2018 at 14:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.