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.
goto done; // ... done: std::cout << "finished\n";
Try it
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.
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
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
tryblock 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
gototo emulate loops or state machines whenswitchinside a loop will do. - Compilers can optimize structured control flow at least as well as
goto. - Avoid
gotoinconstexprfunctions: it was forbidden there before C++23, and structured loops always work.