Hacker News new | ask | show | jobs
by jandrewrogers 4209 days ago
Contrary to popular reputation, there are a handful of use cases where "goto" makes the code simpler, cleaner, more readable, and (in rarer cases) faster. In these cases, you should use goto statements. A good programmer can recognize these cases and use goto appropriately. Goto is never necessary in a strict sense but occasionally it can eliminate some pretty ugly spaghetti code.

The use cases for goto I see are primarily complex/thorough error handling (e.g. unwinding some concurrency control mechanisms) and certain low-level state machine patterns. I would expect to see these kinds of use cases in the Linux kernel.

5 comments

And C doesn't have exceptions, which otherwise would cover a lot of where goto's are used.
There is a difference though. Exceptions can result in Stack Unwinding which is costly. Gotos are a jump which costs literally nothing.
In practice you will do the same thing as unwinding the stack. You'll jump to the end of a function where you'll likely free some heap buffers on your way out and you'll return error status to the caller. What will likely happen next is the caller will bubble up the error: free buffers and report error status to their caller. It works out to pretty much the same thing as a modern C++ code base using RAII, just more manual.
It does have longjmp, which can do basically the same, just without safety (surprise!)
Seems like they use it for most of the error handling, that's true. Almost as many of these as there are switch statements (and 1/3 of if statements). It would be cool if someone could analyze keywords from different projects. Maybe one could give that as use cases in universites instead, that would seem to be alot more practical.

EDIT: Upon closer inspection it seems like even if 'gotos' make everything nastier the extra added performance is worth it.

As long as they're local I guess, like a handmade `finally` clause. It's like mutation in functional programming languages, they're allowed as long as they don't leak. IIRC Zed Shaw's Learn C the Hard Way has some nice `goto` examples..
Breaking from nested loops with goto is also cleaner and simpler. Which is actually one of the reasons some higher level languages even have a goto statement.
For that use-case in particular, a "labeled break" is an alternative that some languages use (like java). I somewhat semantically prefer it if given the choice (name the loop being broken, vs. naming the end-point to jump to), though that preference isn't strong.
Ah yes, the "good" programmer that is well versed in when goto statements are warranted.