Friday, January 13, 2012

2.5. The "goto" statement

The C# language also allows the use of command "goto" for unconditional jumps. Its use is generally not advised, because it can lead to programs full of jumps, and difficult to read. But in specific cases, it can be very useful, for example if we need to exit a very nested loop:

The format of "goto" is

   goto placeToJump;

and jumping position is indicated by its name followed by a colon (:)

   placeToJump:

as in the following example:

/*---------------------------*/
/*  C# Example #26:          */
/*  example26.cs             */
/*                           */
/*  "for" and "goto"         */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example26
{
  public static void Main()
  {

    int i, j;

    for (i=0; i<=5; i++)
        for (j=0; j<=20; j+=2)
        {
            if ((i==1) && (j>=7))
                goto exitPoint;
            Console.WriteLine("i is {0} and j is {1}.", i, j);
        }

    exitPoint:
        Console.Write("End of program");
   
  }
}


 The result of this program is:

  i is 0 and j is 0.
  i is 0 and j is 2.
  i is 0 and j is 4.
  i is 0 and j is 6.
  i is 0 and j is 8.
  i is 0 and j is 10.
  i is 0 and j is 12.
  i is 0 and j is 14.
  i is 0 and j is 16.
  i is 0 and j is 18.
  i is 0 and j is 20.
  i is 1 and j is 0.
  i is 1 and j is 2.
  i is 1 and j is 4.
  i is 1 and j is 6.
  End of program

We can see that when i=1 and j>= 7, we leave both "for" loops.

No comments:

Post a Comment