Goto Hell

The only reason anyone learns about the C language keyword goto is because it’s one of the original 32 keywords. The next thing a programmer learns is to avoid it. Peril, pestilence, and pain awaits the fool who uses goto. Yea verily, if a programming Hell exists, goto is the command you use to get there.

Still, wizards Brian Kernighan and Dennis Ritchie sought to include goto in the C language. It could have been a holdover from the B language or, in their wisdom, they figured it had purpose that no other tool could address. Yet, I can’t think of any situation where an experienced programmer has tossed up his hands and relented to use goto in his code.

In their original edition of The C Programming Language, Kernighan and Ritchie write:

C provides the infinitely-abusable goto statement, and labels to branch to. Formally, the goto is never necessary, and in practice it is almost always easy to write code without it.

I remember using goto in the BASIC programming language. It’s an unconditional branching statement that alters program flow. Most frequently, it’s used with an if statement because BASIC (at the time) lacked a way to group statements as the curly brackets do in C:

IF X = 0 GOTO 40

The problem with goto, and all of early BASIC, is that it disrupts program flow to the point that code is difficult to read and follow. Some programmers preferred things that way, specifically to obfuscate their work and prevent others from copying it. Such “spaghetti code” lead to the demise of BASIC, despite later efforts to improve the language.

As an example of spaghetti code, consider the following:

#include <stdio.h>

int main()
{
    puts("This is Line 1");
    goto this;
that:
    puts("This is Line 3");
    goto theother;
backhere:
    puts("This is Line 5");
    goto end;
this:
    puts("This is Line 2");
    goto that;
theother:
    puts("This is Line 4");
    goto backhere;
end:

    return(0);
}

What a mess!

Each goto statement references a label. In C, a label is a word (named like a variable) followed by a colon. The label typically begins a line, as shown above where goto causes program to hippity-hoppity from place to place. The code could easily be re-written in a variety of ways, but my point was to show how goto can turn things ugly quick. Here’s the output:

This is Line 1
This is Line 2
This is Line 3
This is Line 4
This is Line 5

Internally, goto is a necessary part of computer programming. At the machine code level, a goto is known as a “jump.” It’s a way to load the processor’s instruction pointer (IP) with a specific memory address. Machine code features a lot of jumps, some conditional but many direct. Even Kernighan and Ritchie mention that goto could be necessary in extreme cases. I’ll explore this topic in next week’s Lesson.

Leave a Reply