Lesson 76 +10 XP

Goto Statements

Goto Statements

The goto statement jumps straight to a labeled line in the code. It exists in the language, but most programmers never use it.

The shape

goto skip;   // jump to the label

cout << "never runs" << endl;

skip:
cout << "hello" << endl;
  • Write a label as a name followed by a colon.
  • goto skip; sends execution to that label.
  • Every line in between is skipped.

The spaghetti code problem

Jumping around freely makes the flow of the program hard to follow. A function full of gotos can tangle into spaghetti code, and bugs hide in the knots. LearnCpp 8.7 explains that goto is allowed, but experts avoid it; the flow is easier to trace without the jumps.

Loops are the better tool

Anything a goto can do, a loop or a function call usually does far more clearly. Prefer while, for, break, and return to keep the flow readable.

TL;DR

  • goto label; jumps straight to a label like label:.
  • A label is a name plus a colon.
  • Heavy use of goto creates hard to follow, spaghetti style code.
  • Prefer loops, break, and return instead.