The goto
statement transfers the control of the program immediately to a labeled statement (Docs, 2015).
Even though goto
is useful in jumping out of a deeply nested loop, the use of goto statement is highly discouraged as it often results in spaghetti code:
…widespread and unconstrained use of GOTO statements has led to programmers producing inconsistent, incomplete and generally unmaintainable programs.
Such code is often known as ‘spaghetti’, given its convoluted and tangled control structure.
The previous nested for
loop
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (j > i)
{
break;
}
Console.Write($"{j}");
}
Console.WriteLine();
}
can be written using goto
as
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (j > i)
{
goto outer;
}
Console.Write($"{j}");
}
outer:
Console.WriteLine();
}
Note that we need a label (outer:
in the example above) to indicate the position we want the program control to go.
Live-code example
References
- Docs, M. (2015, July 20). goto (C# Reference). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto
- Cram, D., & Hedley, P. (2005). Pronouns and procedural meaning: The relevance of spaghetti code and paranoid delusion. Oxford University Working Papers in Linguistics, Philology and Phonetic, 10, 187–210.