Team LiB
Previous Section Next Section

Jump Statements

Some of the loops and flow of control structures we've discussed will exit automatically when a condition is met (or not met) and some of them will not. The C# language defines a number of jump statements that are used to redirect program execution to another statement elsewhere in the code. The two types of jump statement that we'll discuss in this section are the break and continue statements. Another jump statement, the return statement, is generally used to exit a method. We'll defer our discussion of the return statement until Chapter 4.

We've already seen break statements in action earlier in this chapter, when they were used in conjunction with a switch statement. A break statement can also be used to abruptly terminate a do, for, or while loop. When a break statement is encountered during loop execution, the loop immediately terminates, and program execution is transferred to the line of code immediately after the loop or flow of control structure.

The output produced by the code in the preceding example would be as follows:

1
2
Loop finished

A continue statement, on the other hand, is used to exit from the current iteration of a loop without terminating overall loop execution. A continue statement transfers program execution back up to the top of the loop without finishing the particular iteration that is already in progress.

The output produced by this code would be as follows:

1
2
4
Loop finished

Team LiB
Previous Section Next Section