The syntax of the goto statement
What you'll learn: How to define a destination label and trigger a jump to it using the goto keyword.
In C, your code usually flows like water in a straight pipe, moving from the top line to the bottom. The goto statement is like a "teleporter" that breaks this flow, instantly moving the program's execution to a specific, named location elsewhere in the same function.
Defining the destination: Labels
Before you can teleport, you need a destination. In C, this is called a label. A label is simply an identifier (a name you choose) followed by a colon :.
Think of a label like a bookmark in a book. It doesn't "do" anything by itself; it just marks a spot so you can find it later. You can place a label on its own line above any statement you want to jump to.
Using the goto keyword
Once you have a label, you use the goto keyword followed by that label's name and a semicolon to perform the jump. When the computer hits a goto line, it stops what it’s doing and immediately restarts execution at the line marked by the corresponding label.
Here is how the syntax looks in practice:
#include <stdio.h>
int main() {
printf("First, we do this.\n");
goto skip_ahead; // The teleport command
printf("This line will be ignored completely.\n");
skip_ahead: // The destination label
printf("Suddenly, we are here!\n");
return 0;
}
The rules of the jump
There are two important syntax rules to remember:
- The Colon: The label destination ends with a colon (
my_label:), but thegotocommand ends with a semicolon (goto my_label;). - The Scope: You can only jump to a label within the same function. You cannot use
gototo hop frommain()into a different function you've written.
While goto is often discouraged in modern programming because it can make code messy (often called "spaghetti code"), understanding its syntax is vital for reading older C programs or handling complex error cleanup.
Key takeaway
The goto statement requires a named label followed by a colon (label_name:) to act as a destination, allowing the program to jump directly to that line.