goto

What Is the goto Command?

The goto command is a jump statement in C and C++ that needs a label to jump to. Here is how the two parts fit, with a full example and common mistakes.

On this page
  1. The two parts of a goto command
  2. Rules for matching the two parts
  3. A complete program
  4. What a mistake looks like
  5. Why the word command can confuse
  6. Next steps

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 goto must match the label exactly. Names are case-sensitive, so Done and done are 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.

The complete guide to goto

How to Use goto in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Heap vs Stack Memory in C++

Learn how heap and stack memory differ in C++: how each is allocated, how long data lives, the speed and size trade-offs, and common mistakes, with examples.

Heap vs Stack 5 min read