C Programming

Is Goto Always Evil?

Situations where labeled branching makes your C code better

Don Cross
Level Up Coding
Published in
5 min readMay 19, 2020

--

Photo by Trevor Cole on Unsplash

In 1968, Edgar Dijkstra wrote the influential essay Go To Statement Considered Harmful. He argued that the use of unconditional branches, commonly known as goto statements, should be abolished from high level programming languages.

The animosity against goto statements is well-deserved. Everyone who has programmed in BASIC or older dialects of FORTRAN has struggled with tangled masses of spaghetti logic. Dense sequences of statements laden with interwoven networks of goto statements are hard to understand and even harder to maintain.

Most of the time, it’s more elegant to use block-structured programming. Constructs like if, while, and switch make your code’s intent clear.

And yet, more than 50 years after Dijkstra’s abolitionist manifesto, C and other languages still include a goto statement. Although goto remains taboo, its use is still possible. Is goto ever justified? Should it be completely wiped from the face of the Earth?

I argue there are cases in C programs where goto is helpful.

Unconditional branching is a tool. Some tools, such as chainsaws, are dangerous. We don’t want people running around recklessly swinging chainsaws everywhere. This does not mean that chainsaws should be banned. There are situations where careful use of a chainsaw is the best choice.

When is goto a wise choice? Here are two scenarios where it has merit.

Exiting Multiple Nested Loops

C and other programming languages recognize the widespread need to leave a loop early. C provides the break statement for this purpose. A break statement is a variant of goto. It is an unconditional branch that jumps out of its containing for, while, or switch, instead of to an explicit label.

Sometimes we would like to break out of more than one nested loop. Suppose we have inherited some code that prints the contents of a 3-by-3 array of integers:

--

--