What is wrong with using goto?

There is nothing wrong with goto in itself. It's a very useful construct in programming and has many valid uses. The best that comes to mind is structured resource freeing in C programs.

Where goto's go wrong is when they are abused. Abuse of gotos can lead to thoroughly unreadable and unmaintainable code.


Because they lead to spaghetti code.

In the past, programming languages didn't have while loops, if statements, etc., and programmers used goto to make up the logic of their programs. It lead to an unmaintainable mess.

That's why the CS gods created methods, conditionals and loops. Structured programming was a revolution at the time.

gotos are appropriate in a few places, such as for jumping out of nested loops.


Nothing is wrong with goto if it is used properly. The reason it is "taboo" is because in the early days of C, programmers (often coming from an assembly background) would use goto to create incredibly hard-to-understand code.

Most of the time, you can live without goto and be fine. There are a few instances, however, where goto can be useful. The prime example is a case like:

for (i = 0; i < 1000; i++) {
    for (j = 0; j < 1000; j++) {
        for (k = 0; k < 1000; k++) {
            ...
            if (condition)
                goto break_out;
            ....
        }
    }
}
break_out:

Using a goto to jump out of a deeply-nested loop can often be cleaner than using a condition variable and checking it on every level.

Using goto to implement subroutines is the main way it is abused. This creates so-called "spaghetti code" that is unnecessarily difficult to read and maintain.

Tags:

C++

Goto