goto statement - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# goto statement

From cppreference.com
< c‎ | language

Transfers control unconditionally to the desired location.

Used when it is otherwise impossible to transfer control to the desired location using conventional constructs.

### [edit] Syntax

`goto` label |  |
label `:` |  |

### [edit] Explanation

The goto statement transfers control to the location, specified by label. The goto statement must be in the same function as the label it is referring. If goto statement transfers control backwards, all objects, that are not yet initialized at the label 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

`goto`

### [edit] Example

Run this code

    /* 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

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=c/language/goto&oldid=70237"