The two parts of a goto command
A goto command has two parts. The goto statement is the jump. The label is the target: a name written in front of a statement elsewhere in the same function.
goto label_name; // part 1: the jump
label_name: // part 2: the target label
statement;
Rules for matching the two parts
- The name after
gotomust match the label exactly. Names are case-sensitive, soDoneanddoneare different labels. - Label names follow the same rules as other identifiers: letters, digits and underscores, with no leading digit. They cannot be keywords.
- The label goes at the start of a statement, followed by a colon.
- The label can come before or after the
goto, as long as both are in the same function. - Each label name can appear only once in a function.
A complete program
#include <iostream>
int main() {
int temperature = 35;
if (temperature > 30) {
goto hot;
}
std::cout << "Not hot today\n";
return 0;
hot:
std::cout << "It is hot today\n";
return 0;
}
With temperature set to 35, the condition is true, the jump lands on hot:, and the program prints “It is hot today”. Change the value to 20, and the program prints “Not hot today” instead.
What a mistake looks like
If the goto names a label that does not exist, the compiler stops with an error. The same happens when the goto is in one function and the label is in another, because labels do not cross function boundaries.
int main() {
goto finish;
return 0;
}
This program fails to compile, because the label finish is never defined.
Why the word command can confuse
The word command has other meanings. Windows batch files have their own goto command, which jumps to a label written as :name. Older BASIC dialects used line numbers after GOTO instead of names. In this article, the goto command means the C and C++ statement.
Next steps
Once the two parts are clear, how to use goto in c covers where a jump may land and what it may skip.