A couple of weeks ago, I wrote about Vivek Haldar’s discussion of Dijkstra’s famous paper on why you shouldn’t use gotos in higher order languages. Dijkstra’s admonition has become received wisdom these days to the point of becoming a shibboleth that many recite without any understanding of Dijkstra’s point or why gotos should be avoided.
Haldar is back with another video that discusses a couple of cases where gotos are not only appropriate but the right choice. The first case is to enable a quick exit from a series of complicated code when an error is detected. Most of the time, a simple return statement will suffice but sometimes there’s cleanup code that needs to be run. You could, in principal, accomplish this with a really nasty set of complicated (especially if there is more than one such need to exit) if statements but that makes the code ugly and hard to read. Not convinced? Consider that the Linux kernel has over 13,000 such gotos doing exactly that. It’s a common strategy among experienced engineers and less experienced engineers shouldn’t let superstition about the evilness of all gotos keep them from using it to advantage.
The other case is a little more technical. The idea is to replace a large switch statement with what amounts to a jump table of precomputed gotos. The common application of this is in an interpreter where the main loop looks at each pseudo-op and uses a switch statement to perform the desired operation. Significant speed increases (\(\approx 25\%\)) can be realized with that strategy. The technique is used, for example, in the Python interpreter.
Take a look at Haldar’s video for more details. Good engineers can, and do, disagree as to when, if ever, gotos are appropriate but Haldar’s video will give you some tools to decide for yourself whether a particular case is justified or not.