Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Keywords and Statements

The goto statement

Reference for C++ goto: labels, jumping within a function, what you may not jump over, how destructors behave, and better alternatives.

goto label; transfers control unconditionally to a statement marked with label: in the same function. It is the most primitive control-flow statement in the language, and nearly everything it does is expressed more clearly with loops, break, return, functions or RAII.

C++ restricts goto more than C does. You may jump out of scopes (locals are destroyed in the right order), but you may not jump forward past the initialization of a variable into its scope. Jumping backwards over a declaration is allowed and destroys the object first.

C++
    goto done;
    // ...
done:
    std::cout << "finished\n";

Try it

C++ Leaving nested loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Destructors run when you jump out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
label: statement
goto label;
Part Description
label An identifier followed by : in front of a statement. Labels have function scope: they are visible in the whole function, even before the label appears. They live in their own namespace, separate from variables and types.
goto label; Jumps to the statement the label marks. The label must be in the same function.

Usage notes

  • A jump that bypasses a declaration with initialization (int x = 5;) and lands inside the variable's scope is ill-formed (GCC reports "jump to label crosses initialization").
  • Jumping out of a block runs the destructors of its automatic objects in reverse order, so RAII keeps working. You cannot jump into a try block or a handler.
  • A label needs a statement after it. To put a label at the very end of a block, follow it with a null statement (label: ;).
  • The usual legitimate uses are leaving deeply nested loops and retry loops. Prefer a helper function with return, or a lambda, for the first case.
  • Never use goto to emulate loops or state machines when switch inside a loop will do.
  • Compilers can optimize structured control flow at least as well as goto.
  • Avoid goto in constexpr functions: it was forbidden there before C++23, and structured loops always work.