goto is a jump to a labeled statement
goto is a jump statement in C and C++. When the program reaches it, execution moves to a labeled statement elsewhere in the same function, and the lines in between do not run. Both languages reserve goto as a keyword, so it cannot be used as a variable or function name.
What the jump does
Programs normally run statements from top to bottom. Loops, if statements and function calls change that order in structured ways, and each has a clear start and end. goto changes the order directly. It does not call a function, and it does not return to where it came from. The program simply continues at the label.
Here is a small example:
#include <iostream>
int main() {
std::cout << "Checking the input\n";
bool input_ok = false;
if (!input_ok) {
goto report_error;
}
std::cout << "Input is fine\n";
return 0;
report_error:
std::cout << "Input is not valid\n";
return 1;
}
With input_ok set to false, the program prints “Checking the input” and “Input is not valid”, then exits with status 1. The line “Input is fine” never runs.
Where the name comes from
goto is short for “go to”. In 1968, the computer scientist Edsger Dijkstra published a letter titled “Go To Statement Considered Harmful”. He argued that unrestricted jumps make programs hard to understand and hard to check. The letter started a long debate, and most modern style guides steer programmers away from goto.
Is goto still used?
Yes, but rarely in everyday C++. You will see it in older code and in some C programs. The Linux kernel and other C projects use it to clean up after an error partway through a function. In C++, much of that cleanup is handled by objects that release their resources when they go out of scope. Code usually reads better with break, continue, return and functions. For leaving a loop early, a break statement in c is usually enough, with no label needed.
Writing one correctly
Reading a goto is easier than writing one. A label must be in the same function, have a unique name, and sit in front of a statement. C++ also rejects some jumps that skip over variable declarations. The full rules are in how to use goto in c.
Key points
gotojumps to a label in the same function.- The jump skips the lines between the
gotoand the label. - Dijkstra’s 1968 letter is a big reason many programmers avoid it.
- Modern C++ code seldom needs it, because
break,continueandreturncover most cases.