6.12. The goto StatementA goto statement provides an unconditional jump from the goto to a labeled statement in the same function.
The syntactic form of a goto statement is
goto label;
where label is an identifier that identifies a labeled statement. A labeled statement is any statement that is preceded by an identifier followed by a colon: end: return; // labeled statement, may be target of a goto The identifier that forms the label may be used only as the target of a goto. For this reason, label identifiers may be the same as variable names or other identifiers in the program without interfering with other uses of those identifiers. The goto and the labeled statement to which it transfers control must be in the same function. A goto may not jump forward over a variable definition: // ... goto end; int ix = 10; // error: goto bypasses declaration statement end: // error: code here could use ix but the goto bypassed its declaration ix = 42; If definitions are needed between a goto and its corresponding label, the definitions must be enclosed in a block: // ... goto end; // ok: jumps to a point where ix is not defined { int ix = 10; // ... code using ix } end: // ix no longer visible here A jump backward over an already executed definition is okay. Why? Jumping over an unexecuted definition would mean that a variable could be used even though it was never defined. Jumping back to a point before a variable is defined destroys the variable and constructs it again:
// backward jump over declaration statement ok
begin:
int sz = get_size();
if (sz <= 0) {
goto begin;
}
Note that sz is destroyed when the goto executes and is defined and initialized anew when control jumps back to begin:.
|