🔁 C++ Control Flow
Estimated reading: 2 minutes 352 views

C++ goto Statement – Jump to a Label in Your Code


Introduction – What Is the goto Statement in C++?

The goto statement in C++ provides a way to transfer control unconditionally to another part of the program by jumping to a labeled statement. While powerful, it is rarely used in modern C++ programming due to its tendency to create unstructured and hard-to-follow code.

In this guide, you’ll learn:

  • Syntax of the goto statement
  • How labels and jumps work
  • Examples of valid and poor use cases
  • Best practices and alternatives to goto

Syntax of goto Statement

goto label;
// code skipped
label:
    // destination code block

Example – Basic goto Usage

int x = 5;

if (x == 5) {
    goto skip;
}

cout << "This line is skipped";

skip:
cout << "Jumped to label";

Output:

Jumped to label

goto for Exiting Nested Loops

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (i == j) goto end;
        cout << i << ", " << j << endl;
    }
}
end:
cout << "Exited loops";

Common Mistakes

Mistake Fix
Using goto instead of loopsUse while or for for structured iteration
Creating spaghetti codeUse functions to encapsulate logic instead
Jumping over variable declarationsAvoid jumping past local declarations with constructors

Best Practices

  • Avoid goto unless absolutely necessary
  • Use for exiting deeply nested loops or error handling in low-level systems
  • Replace with functions, break, continue, or return where possible

Summary – Recap & Next Steps

Key Takeaways:

  • goto jumps to a labeled part of code, bypassing structure
  • Useful in limited cases like breaking nested loops
  • Considered bad practice for regular control flow
  • Prefer structured constructs like loops and functions

Real-World Relevance:
Still occasionally used in embedded systems, system-level code, or legacy C++ projects where structured constructs are limited.


FAQs – C++ goto Statement

Is goto bad in C++?
Generally yes. It makes code harder to follow and maintain.

Can I use goto to jump backward in code?
Yes, but be cautious. It can create loops or unintentional infinite jumps.

Is goto allowed in modern C++?
Yes, but it’s discouraged in favor of structured programming.

Can goto jump into another function?
No. You can only jump within the same function.

What is a good use of goto?
Exiting nested loops or in very low-level programming, such as error cleanup.


Share Now :
Share

C++ goto Statement

Or Copy Link

CONTENTS
Scroll to Top