Course contentsShow
← C
Lesson 307 of 1,2194. Control FlowFree lesson

The syntax of the goto statement

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:

  1. The Colon: The label destination ends with a colon (my_label:), but the goto command ends with a semicolon (goto my_label;).
  2. The Scope: You can only jump to a label within the same function. You cannot use goto to hop from main() 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.