goto
StatementA goto
statement provides an unconditional jump from the goto
to a another statement in the same function.
Programs should not use goto
s. goto
s make programs hard to understand and hard to modify.
The syntactic form of a goto
statement is
goto label;
where label is an identifier that identifies a statement. A labeled statement is any statement that is preceded by an identifier followed by a colon:
end: return; // labeled statement; may be the target of a goto
Label identifiers are independent of names used for variables and other identifiers. Hence, a label may have the same identifier as another entity in the program without interfering with the other uses of that identifier. The goto
and the labeled statement to which it transfers control must be in the same function.
As with a switch
statement, a goto
cannot transfer control from a point where an initialized variable is out of scope to a point where that variable is in scope:
// . . .
goto end;
int ix = 10; // error: goto bypasses an initialized variable definition
end:
// error: code here could use ix but the goto bypassed its declaration
ix = 42;
A jump backward over an already executed definition is okay. Jumping back to a point before a variable is defined destroys the variable and constructs it again:
// backward jump over an initialized variable definition is okay
begin:
int sz = get_size();
if (sz <= 0) {
goto begin;
}
Here sz
is destroyed when the goto
executes. It is defined and initialized anew when control passes back through its definition after the jump back to begin
.