goto statement
Transfers control unconditionally to the desired location.
Used when it is otherwise impossible to transfer control to the desired location using conventional constructs.
Contents |
[edit] Syntax
goto identifier ;
|
|||||||||
identifier : statement
|
|||||||||
[edit] Explanation
The identifier in a goto statement names a label located somewhere in the enclosing function. The goto statement transfers control to the statement prefixed by the named label in the enclosing function.
The goto statement must be in the same function as the identifier it is referring. If a goto statement transfers control backwards, all objects, that are not yet initialized at the identifier are destructed. It is not allowed to transfer control forwards if doing so would skip initialization of an object.
A label name is an identifier followed by a colon (:) and a statement. A label name has function scope.
[edit] Keywords
[edit] Example
/* Using 'goto' in the contexts of the three control structures of structured */ /* programming: sequence, branch, and loop. */ #include <stdio.h> int main(void) { /* Sequence control structure */ /* Exhibits an example of an error. */ /* goto label_1; { int i=888; error: crosses initialization of 'int i' label_1: printf("i = %d\n", i); } */ /* Branch control structure */ /* The break statement is usually used here, but 'goto' can redirect to */ /* any location. */ int sw = 2; switch (sw) // integral expression { case 1: printf("case 1\n"); goto label_2; // end case 1 case 2: printf("case 2\n"); goto label_2; // end case 2 case 3: printf("case 3\n"); goto label_2; // end case 3 } label_2: ; /* Loop control structure */ /* Using two 'goto' statements to simulate "while (i<5) {}". */ int i = 0; top_of_loop: if (!(i<5)) goto label_3; printf("i = %d\n", i); ++i; goto top_of_loop; label_3: printf("exit\n"); return 0; }
Output:
case 2 i = 0 i = 1 i = 2 i = 3 i = 4 exit