March 5, 2014 at 12:57 AM by Dr. Drang
Now that everybody’s had their say on Apple’s
goto fail bug and no one cares anymore, I thought I’d chime in. Specifically, I want to push back a bit against a couple of things said at the end of last week’s ATP episode.
Both John and Marco defended Apple’s use of
goto, arguing that it’s the standard way to jump to error handling code in C. I don’t disagree. However, they implied that being reproached for using
goto is a relatively new thing, something done by people used to the exception handling built into more modern languages and not familiar with older languages like C. Nothing could be further from the truth.
Here’s John’s punch line:
The only thing you’ve heard about programming is that
gotois evil because there’s a paper that you never read that got passed around the internet ten years ago.
The paper “that got passed around the internet ten years ago” is this one by Edsger Dijkstra, a guy who was kind of important in the development of computer science. “Go to statement considered harmful” was written in 1968 and was pretty clearly not a response to C idioms because C didn’t exist yet. It was one of the seminal papers in the move to structured programming from languages like Fortran and Cobol, and yes, I have read it.
I suspect Dennis Ritchie read it, too. C was influenced by Algol, and its design owes much to the ideas of structured programming. C, of course, does have a
goto statement, but it’s a kinder, gentler
goto than those of earlier languages. C’s
goto can’t jump out of a function, which makes it at least semi-structured.
Donald Knuth read Dijkstra’s paper and wrote a very long response, which came out in 1974. He defended certain uses of
goto and probably would have been happy with K&R’s example above. It’s unfair to boil Knuth’s paper down to a single sentence, but if I had to, it’d be “Let’s not throw the baby out with the bath water.”
So, admonitions against
goto aren’t new, aren’t about C, and certainly aren’t predicated on ideas taken from modern languages with exception handling. The arguments for and against
goto are part of a long tradition of programmers trying to figure out how to write code that’s easier to understand and more likely to be correct.
One last thing. Marco said something that even the mild-mannered Casey snorted at in derision:
And there’s things like
continuein a loop. I would argue that
break, are really not a whole lot cleaner than
I would argue that this is nuts.
continue are exactly the kinds of commands Dijkstra wanted programmers to have so they could avoid
gotos. The difference is that
continue are bound to their block; they don’t need labels because there’s only one place they can go.
goto needs a label precisely because it can jump anywhere.