1.12. Jump Statements

Some of the loops and flow of control structures we have 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 statements that we will discuss in this section are the break and continue statements. Another jump statement, the return statement, is used to exit a method. We will defer our discussion of the return statement until Chapter 4.

You have 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.

// This loop is intended to execute four times...
for (int j = 1; j <= 4; j++) {
  //...but, as soon as j attains a value of 3, the following 'if'
  // test passes, the break statement that it controls executes, and we
  // 'break out of' the loop.
  if (j == 3)
     break;

  // If, on the other hand, the 'if' test fails, we skip over the
  // 'break' statement, print the value of j, and keep on looping
  Console.WriteLine(j);
}

// The break statement, if/when executed, takes us to this line of code
// immediately after the loop.
Console.WriteLine("Loop finished");

The output produced by the preceding code snippet 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 (to the iterator part of a for loop) without finishing the particular iteration that is already in progress.

// This loop is intended to execute four times...
for (int j = 1; j <= 4; j++) {
  //...but, as soon as j attains a value of 3, the following 'if' test
  // passes and we 'jump' back to the j++ part of the for statement,
  // with j being incremented to 4...
  if (j == 3)
     continue;

//...and so the following line doesn't get executed when j equals 3,
  // but DOES get executed when j equals 1, 2, and 4.
  Console.WriteLine(j);
}
Console.WriteLine("Loop finished");

The output produced by this code would be as follows:

1
2
4
Loop finished

Excessive use of break and continue statements in loops can result in code that is difficult to follow and maintain, so it's best to use these statements only when you have to use them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset