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

The dangers of 'spaghetti code'

The dangers of 'spaghetti code'

What you'll learn: Why the goto statement is generally avoided in modern C programming due to its impact on code readability and logic.

The "Teleportation" Problem

In C, code usually flows like a waterfall: it starts at the top and moves downward, line by line. Even with loops and if-statements, there is a clear logic to follow. The goto statement breaks this rule. It allows you to jump from your current line to any other labeled part of your function instantly.

Think of it like reading a recipe. Normally, you follow steps 1 through 5. A goto statement is like a step that says, "Now jump to the middle of a different recipe on page 42." If you use too many of these jumps, your program’s logic becomes tangled, intertwined, and impossible to follow—much like a bowl of tangled pasta. This is why programmers call messy, unorganized logic spaghetti code.

Why it’s dangerous

When you use goto, you lose the ability to reason about the "state" of your program. If you jump into the middle of a complex calculation, you might skip over a line that was supposed to initialize a variable or open a file. This leads to bugs that are incredibly hard to track down because the "path" the computer took to get to a specific line is no longer predictable.

#include <stdio.h>

int main() {
    int x = 0;

    // A 'label' followed by a colon
    start_point: 
    
    printf("Value: %d\n", x);
    x++;

    if (x < 3) {
        goto start_point; // Jumping backwards like a loop
    }

    goto end_point;

    // This code is "dead" and hard to manage
    printf("This will never print.\n");

    end_point:
    printf("Done.\n");

    return 0;
}

When is it okay?

In modern C, almost everything a goto does can be done better with while loops, for loops, or if/else structures. The only time professional C programmers typically use goto is for "cleanup" at the very end of a function—to ensure that if an error happens, the program jumps to a single spot to close all open files and free up memory before exiting. For everything else, keep your "spaghetti" in the kitchen and out of your source code.

Key takeaway

Avoid goto because it creates "spaghetti code" that is difficult to read, debug, and maintain.