Export (0) Print
Expand All

goto

The goto statement transfers the program control directly to a labeled statement. It takes one of the following forms:

goto identifier;
goto case constant-expression;
goto default;

where:

identifier
A label.
constant-expression
A switch-case label.

Remarks

In the first form, the identifier indicates a label located in the current body, the same lexical scope, or an enclosing scope of the goto statement.

A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement.

The goto statement is also useful to get out of deeply nested loops.

A warning message may be issued if the label has never been referenced in the program. For more information on labels, see 3.3 Declarations.

Example

For an example of using goto to transfer control to a specific switch-case label, see the switch example.

Example

The following example demonstrates using goto to break out from nested loops.

// statements_goto.cs
// Nested search loops
using System;
public class GotoTest1 
{
   public static void Main() 
   {
      int x = 200, y = 4;
      int count = 0;
      string[,] myArray = new string[x,y];

      // Initialize the array:
      for (int i = 0; i < x; i++) 
         for (int j = 0; j < y; j++)
            myArray[i,j] = (++count).ToString();      
   
      // Read input:
      Console.Write("Enter the number to search for: ");

      // Input a string:
      string myNumber = Console.ReadLine();

      // Search:
      for (int i = 0; i < x; i++)
         for (int j = 0; j < y; j++)
            if (myArray[i,j].Equals(myNumber))
               goto Found;

      Console.WriteLine("The number {0} was not found.", myNumber);
      goto Finish;

   Found:
      Console.WriteLine("The number {0} is found.", myNumber);

   Finish: 
      Console.WriteLine("End of search.");
   }
}

Input

44

Sample Output

Enter the number to search for: 44
The number 44 is found.
End of search.

Example

// statements_goto2.cs
// CS0159 expected
// Labels outside the scope
using System;
class UnreachableCode 
{
   public static void Main() 
   {
      int x = 55;
      Console.WriteLine("x = {0}", x);

      if (x == 55) 
      {
         x = 135;
         goto A;   // Error
      }

      x = x + 1;

      for (int i=1; i<=5; i++) 
      {
         A: Console.WriteLine(i);       
      }

      Console.WriteLine("x = {0}", x);
   }
}

In the preceding example, the goto statement is referencing a label A outside its scope. The compiler will issue the error message:

No such label 'A' within the scope of the goto statement

A warning message may also be issued because the label has never been referenced.

If you move the label A to the beginning of the for loop, the program would compile and run normally, that is:

A:      for (int i=1; i<=5; i++) {   // Now the program compiles.

See Also

C# Keywords | Compare to C++ | Jump Statements | C. Grammar

Show:
© 2014 Microsoft