Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

goto — unconditional jump to a label

The goto statement unconditionally transfers control to a named label in the same function. It can exit multiple nested loops, but remains subject to the rules for initializing and destroying local objects.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

goto identifier;
identifier: statement

goto identifier; transfers control to the label identifier: in the same function; it is not a function call. The target may appear earlier or later in the code. Label names must be unique within a function.

A jump must not enter the scope of a local variable with automatic storage duration while bypassing required initialization. For example, jumping past int x = 1; to a label within the scope of x is a compilation error. There is an exception for vacuous initialization as defined by the standard; nevertheless, do not treat goto as a way to bypass initialization.

When a jump exits scopes, local objects with automatic storage duration are destroyed in reverse construction order. Thus, goto does not bypass those objects' destructors.

In the example, goto done; exits both loops after finding the first matching pair. Prefer loops, break, return, or extracting a function when they express the intent more clearly; jumps can make control flow harder to follow.

This entry targets C++23. The supplied source is an evolving working draft, not a frozen C++23 publication. The flag -std=c++23 selects the compilation mode for local verification; production runtime behavior is not attested.

Examples

#include <iostream>

int main() {
    int found = -1;

    for (int row = 0; row < 3; ++row) {
        for (int col = 0; col < 3; ++col) {
            if (row + col == 3) {
                found = row * 10 + col;
                goto done;
            }
        }
    }

done:
    std::cout << found << '\n';
}

Result

12

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources