When to use Break and Continue

This is a fairly simple yet useful difference to know between break and continue when using loops or switch statements. The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.  The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears.   I find this wording from msdn to be slightly confusing so let’s turn to some examples.

Take this loop for instance:

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

    TestMethod(i);
}

The use of break in the above example causes the loop to exit on the first iteration of the loop. This means that our TestMethod(i) will never be executed.  This works well if you are looking through a list for a particular value, once found, there is no need to iterate through everything else.

Now let’s take a look at the continue statement:

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

    TestMethod(i);
}

The use of the continue statement above causes the loop to skip calling the TestMethod(i) when i  == 0.  However, the iterations will continue after that and TestMethod(i) will be executed when i  == 1 all the way to i == 99.  This comes in handy if there are certain values in a list that you are not wanting to execute on; you can skip over them and continue on with executing on the rest of the values in the list.

Some closing thoughts, in whether this is best practice or not it’s debating frequently.  The main argument that arises is code readability.  If you are having a hard time reading the code this will raise the chances of you exiting before you are wanting to and can cause bugs that you do not realize.  So as always, make sure you pay attention to what you are doing and what your intent is to ensure that your program is going to perform properly.


StackOverflow Profile