5 ms·
The use of goto[1] in this code surprises me. Isn't use of it still generally shunned? Appearing in the Linux kernel makes me reconsider my avoidance of it[2].
by hartror 15y ago
The use of goto[1] in this code surprises me. Isn't use of it still generally shunned?
Appearing in the Linux kernel makes me reconsider my avoidance of it[2]. A quick google throws up a discussion with Linus in 2003[3] which can be summarised as: don't blame the tool, blame the programmer and as a tool goto has a place.
[1] XKCD comic on the subject http://xkcd.com/292/ http://xkcd.com/292/
[2] On my infrequent visits to C++ land, I generally live in Python land where goto doesn't exist.
[3] http://kerneltrap.org/node/553/2131 http://kerneltrap.org/node/553/2131
- zx2c4 15y agoGoto is common for error out code in C. The code that uses that mentioned in the blog code is from the linux kernel, not any exploit code. But please, for the love of god, can we not make this discussion thread an extended conversation on the merits or horrors of goto? Pretty please?
- VMG 15y agometa: I don't see why it is necessary to downvote newbie questions on HN
- yew 15y agoGoto is actually relatively common in C code. As in this case, it's usually used for error handling in much the same manner as exceptions might be. The document "/usr/src/linux/Documentation/CodingStyle" actually recommends such usage.
- fhars 15y agoRead the classics http://scholar.google.com/scholar?cluster=17147143327681396418 http://scholar.google.com/scholar?cluster=171471433276813964...
- zokier 15y agoI addition what others have said, I'd emphasise that goto for error handling is fine in C, but in C++ it is usually unnecessary because C++ has exceptions and RAII.
- exDM69 15y agoGotos are common in C for error handling because the other alternative of doing an if/then/else with all the error handling is so verbose. It's used to work around the lack of exceptions in C. You still should not use gotos for regular control flow. And jumping backwards with goto is bad practice in most cases.
- chalst 15y agoThe reason why Linus Torvalds and others prefer to handle errors using goto is that it avoids the main branch of the code receiving an additional indentation, as it would if it were wrapped in a conditional. Not to do so would make the code less readable. Note that these gotos are always local jumps (that is, they are in the same code block), at the same indentation level, and they are forward jumps (so the control flow is much the same as for a conditional). They are easy to understand and audit, and not similar to the goto examples that Dijkstra criticised for making code hard to reason about.
- arnnr 15y agoThis. Also python's execeptions can be treated as limited goto's: http://docs.python.org/faq/design.html#why-is-there-no-goto http://docs.python.org/faq/design.html#why-is-there-no-goto