Information Technology Reference
In-Depth Information
The goto Statement
The
goto
statement unconditionally transfers control to a
labeled statement
. Its general form is
the following, where
Identifier
is the identifier of a labeled statement:
goto
Identifier
;
For example, the following code shows the simple use of a
goto
statement:
bool ThingsAreFine;
while (true)
{
ThingsAreFine = MonitorNuclearReactor();
if ( ThingsAreFine )
Console.WriteLine("Things are fine.");
else
goto NotSoGood;
}
NotSoGood: Console.WriteLine("We have a problem.");
The
goto
statement must be
within
the scope of the labeled statement.
A
goto
statement can jump to any labeled statement within its own block, or
out
to any
block in which it is nested.
A
goto
statement cannot jump
into
any blocks nested within its own block.
■
Caution
Using the
goto
statement is strongly discouraged, as it can lead to code that is poorly struc-
tured, and difficult to debug and maintain. Edsger Dijkstra's 1968 letter to the Communications of the ACM,
entitled “Go To Statement Considered Harmful,” was an important point in the history of computer science; it
was one of the first published descriptions of the pitfalls of using the
goto
statement.
The goto Statement Inside a switch Statement
There are also two other forms of the
goto
statement, for use inside
switch
statements. These
goto
statements transfer control to the correspondingly named switch label in the
switch
statement.
goto case
ConstantExpression
;
goto default;