4 ms·
I've always wondered why goto is actually considered harmful. I really should read the original paper by Djikstra...
by chris_wot 7y ago
I've always wondered why goto is actually considered harmful. I really should read the original paper by Djikstra...
- saagarjha 7y agoIt encourages spaghetti code.
- Someone1234 7y agoNot using it can also create spaghetti code. For example the "alternatives" often suggesting for exiting a multi-tiered loop (which often add additional boilerplate, additional variables, etc that all need to be maintained/bug free).
- FartyMcFarter 7y agoIndeed. Despite not having actual goto, Java went out of their way to have labeled loops and the "break label_name" syntax in order to avoid this awkwardness.
- jjuhl 7y ago[RAII](https://en.cppreference.com/w/cpp/language/raii https://en.cppreference.com/w/cpp/language/raii) to the rescue..
- GrumpyYoungMan 7y agoRead David Tribble's "Go To Statement Considered Harmful: A Retrospective" instead: http://david.tribble.com/text/goto.html http://david.tribble.com/text/goto.html . It contains the entire text of Dijkstra's paper and goes over its meaning in a modern context on a paragraph-by-paragraph basis. It's very well written and makes clear the "encourages spaghetti code" argument, while true at the time, applied in a era where basic control flow constructs that we now take for granted did not exist in commonly used languages.
- nybble41 7y agoThank you for the recommendation; that was a very interesting read. I find that I can't quite agree with the last "nontrivial goto" example, though. This version without explicit gotos is actually shorter, and IMHO not really any more difficult to follow: int parse(void) { Token tok; while ((tok = gettoken()) != END) { while (!shift(tok)) if (!reduce(tok)) return ERROR; } return ACCEPT; } I will say that any language without goto, or where the use of goto is discouraged, should at least provide guaranteed tail-call elimination as an alternative. In this case the gotos could easily be converted into loops, but not every algorithm is so accommodating.
- gbacon 7y agoSee also Structured programming with go to statements[0] by Donald E. Knuth. [0]: https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.103.6084 https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.103...