goto and Labels

Structured Programming vs. goto

Structured programming:

  • Only controlled program flow

  • Loops and branches

  • At most break and continue

    • Only one level concerned

goto is the exact opposite

  • Jump statement out of 10 nested loops

  • ⟶ Massacre

  • Edsger Dijkstra, 1968: “Goto Considered Harmful”

  • ⟶ Plea for structured programming

goto: Definition

C offers easy ways to do what you want

  • Dennis Ritchie: “There is no spirit of C!”

  • Jörg Faschingbauer: there is!

Definition of goto:

  • goto label;

  • label is the name of a place inside the function

  • label is only locally visible

  • Naming rules: like a variable

  • goto can jump to arbitrary places inside the function

goto: Use Cases

Manifold, but …

  • Easily shot in the foot

  • Suggestion: use judiciously error handling

  • Linux Kernel is full of it

int do_complicated_stuff(void)
{
    while (...) {
        ...
        for (...) {
            if (error)
                goto out;
        }
    }
    return 0;
out:
    cleanup_mess();
    return -1;
}