Team LiB
Previous Section Next Section

Jump Statements

The jump statements allow you control program flow by specifying which code blocks should be executed at a certain point in the code. These statements include continue, break, and goto.

continue

There are situations when the execution of code inside a code block should return to the evaluation expression. In C#, this behavior is controlled by the use of the continue statement. When the continue statement is encountered, the conditional expression in the while loop or other flow-control code is evaluated again, and the rest of the code block is skipped.

break

A break statement causes the execution of the code to exit the code block. This statement is usually used in conjunction with a selection statement (if or switch), and it is occasionally used with an iterator statement.

goto

There are two parts to using a goto statement:

  • The first part is a goto command followed by a label.

  • The second part is a label in the method, followed by a semicolon.

Caution 

Be very careful in using the goto statement, because it makes the code much less readable and more difficult to understand.

Upon execution of the goto command, the flow of execution will skip to the first statement following the label.

The following example demonstrates the use of the continue, break, and goto statements.

Code Example: continue, break, and goto
Start example

using System;

namespace Client.Chapter_4___Program_Control
{
      class MyMainClass
      {
            static void Main(string[] args)
            {
                  WhileContinue();
                  WhileBreak();
                  WhileGoto();
            }
            static void WhileContinue()
            {
                  int a = 0;
                  while(a < 10)
                  {
                        a++;
                        if (a == 5)
                        {
                            //Force the execution back to the iterator
                              a++; continue;
                        }
                  }
            }
            static void WhileBreak()
            {
                  int a = 0;
                  while (a < 10)
                  {
                        a++;
                        if (a == 5)
                            //Force the code to leave the iterator
                              break;
                  }
                  a++;
            }
            static void WhileGoto()
            {
                  int a = 0;
                  while (a < 10)
                  {
                        if (a == 5)
                            //Force the code to the code label
                              goto cleanup;
                  }
                  cleanup :
                        Console.WriteLine(a);
            }
      }
}
End example

Team LiB
Previous Section Next Section