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:
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.1 Declarations
For an example of using goto to transfer control to a specific switch-case label, see the switch example.
The following example demonstrates using goto to break out from nested loops.
// Nested search loops using System; using System.IO; public class GotoTest1 { public static void Main() { int x = 200, y = 4; int[,] myArray = new int[x,y]; // initialize the array: for (int i = 0; i < x; i++) for (int j = 0; j < y; j++) myArray[i,j] = ++i; // Read input: Console.Write("Enter the number to search for: "); string s = Console.ReadLine(); // input a char int myNumber = Int32.FromString(s); // Search: for (int i = 0; i < x; i++) for (int j = 0; j < y; j++) if (myArray[i,j] == myNumber) goto Found; NotFound: 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."); } }
Enter the number to search for: 44 The number 44 is found. End of search.
// 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 0159:
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.