The goto Statement 

Performs an unconditional transfer of control to the named label. The

goto identifier ;

Remarks

label must be in the current function.

A statement label is meaningful only to a goto statement; in any other context, a labeled statement is executed without regard to the label.

A jump-statement must reside in the same function and can appear before only one statement in the same function. The set of identifier names following a goto has its own name space so the names do not interfere with other identifiers. Labels cannot be redeclared.

It is good programming style to use the break, continue, and return statement in preference to goto whenever possible. Since the break statement only exits from one level of the loop, a goto may be necessary for exiting a loop from within a deeply nested loop.

For more information about labels and the goto statement, see Labeled Statements and Using Labels with the goto Statement.

Example

In this example, a goto statement transfers control to the point labeled stop when i equals 3.

// goto_statement.cpp
#include <stdio.h>
int main()
{
    int i, j;

    for ( i = 0; i < 10; i++ )
    {
        printf_s( "Outer loop executing. i = %d\n", i );
        for ( j = 0; j < 2; j++ )
        {
            printf_s( " Inner loop executing. j = %d\n", j );
            if ( i == 3 )
                goto stop;
        }
    }

    // This message does not print: 
    printf_s( "Loop exited. i = %d\n", i );
    
    stop: 
    printf_s( "Jumped to stop. i = %d\n", i );
}

Output

Outer loop executing. i = 0
 Inner loop executing. j = 0
 Inner loop executing. j = 1
Outer loop executing. i = 1
 Inner loop executing. j = 0
 Inner loop executing. j = 1
Outer loop executing. i = 2
 Inner loop executing. j = 0
 Inner loop executing. j = 1
Outer loop executing. i = 3
 Inner loop executing. j = 0
Jumped to stop. i = 3

See Also

Reference

Jump Statements (C++)
C++ Keywords