#1,125 – Use of break and continue Statements

You can use the break statement to break out of a loop or switch statement, resuming execution at the endpoint of the enclosing statement.

You can use break within a switch statement or within while, do, for or foreach loops.

You can use the continue statement to jump unconditionally to the endpoint of the body of statements enclosed within a loop.  This will either cause execution to continue with the next iteration of the loop or will continue execution after the loop if the final iteration was being executed.

You can use continue within a while, do, for or foreach loop.

Advertisements

#160 – A while Loop Can Exit on break, goto, return or throw Statements

In addition to completing normally, when the loop expression evaluates to false, a while loop can exit early.  A loop will exit early if it encounters one of the following statements: break, goto, return or throw.

A break statement causes an early exit of the loop and execution to continue with the first statement after the loop.

            uint numTimes = 0;
            while (numTimes < 100)
            {
                WriteOnBlackboard("I will not eat paste");
                if (ChalkBroke())
                    break;     // Stop writing
                numTimes++;
            }

The goto statement can transfer control out of a while loop, to a labeled statement.  Its use is rare, since there are generally more elegant ways to transfer control.

The return statement can transfer control out of a loop and return control to the calling method.

The throw statement transfers control out of a loop and throws an exception, indicating that an error condition occurred.

#156 – Using break and continue in foreach Loops

When iterating through array elements using the foreach statement, you can use the break statement to break out of the loop–when break is encountered, control is transferred to the code immediately following the loop and no more array elements will be processed.

            foreach (Person p in folks)
            {
                Console.WriteLine("{0} {1}", p.FirstName, p.LastName);

                // If we find Elvis, stop the presses
                if (p.FirstName == "Elvis")
                    break;
            }

The continue statement, when encountered in a foreach loop, causes control to transfer back to the top of the loop and move on to the next element.

            foreach (Person p in folks)
            {
                // Don't print out info for any Adolfs; move to the next person
                if (p.FirstName == "Adolf")
                    continue;

                Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
            }