The goto statement is a jump statement that allows the user in the program to jump the execution control to the other part of the program. When encountered in a program, it transfers the execution flow to the labeled statement. The label (tag) is used to spot the jump statement.
NOTE: Although the use of goto is avoided in programming language because it makes it difficult to trace the control flow of a program, making the program hard to understand and hard to modify.
goto statement Flowchart:
Syntax of goto statement in C#:
1 2 3 4 5 6 7 | goto label; .... .... label: statement; //label to jump .... .... statements |
Example of C# goto Statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | // use of goto statement using System; public class GotoStatement { static public void Main() { int selected = 3; switch (selected) { case 1: //this is the label first_case: Console.WriteLine("case: 1"); break; case 2: Console.WriteLine("case: 2"); break; case 3: Console.WriteLine("case: 3"); // transfer the flow to case 1 goto first_case; default: Console.WriteLine("No match found"); break; } } } |
Output:
1 2 | case: 3 case: 1 |