prev up next   top/contents search

comp.lang.c FAQ list · Question 17.10

Q: Some people say that goto's are evil and that I should never use them. Isn't that a bit extreme?

A: Programming style, like writing style, is somewhat of an art and cannot be codified by inflexible rules, although discussions about style often seem to center exclusively around such rules.

In the case of the goto statement, it has long been observed that unfettered use of goto's quickly leads to unmaintainable spaghetti code. However, a simple, unthinking ban on the goto statement does not necessarily lead immediately to beautiful programming: an unstructured programmer is just as capable of constructing a Byzantine tangle without using any goto's (perhaps substituting oddly-nested loops and Boolean control variables, instead). Many programmers adopt a moderate stance: goto's are usually to be avoided, but are acceptable in a few well-constrained situations, if necessary: as multi-level break statements, to coalesce common actions inside a switch statement, or to centralize cleanup tasks in a function with several error returns.

Most observations or ``rules'' about programming style (Structured Programming is Good, goto's are Bad, functions should fit on one page, etc.) usually work better as guidelines than rules, and work much better if programmers understand what the guidelines are trying to accomplish. Blindly avoiding certain constructs or following rules without understanding them can lead to just as many problems as the rules were supposed to avert.

Furthermore, many opinions on programming style are just that: opinions. They may be strongly argued and strongly felt, they may be backed up by solid-seeming evidence and arguments, but the opposing opinions may be just as strongly felt, supported, and argued. It's usually futile to get dragged into ``style wars,'' because on certain issues (such as those referred to in questions 5.3, 5.9, 9.4, and 10.7), opponents can never seem to agree, or agree to disagree, or stop arguing.

Finally, as William Strunk has written (quoted in the Introduction to Strunk and White's classic Elements of Style),

It is an old observation that the best writers sometimes disregard the rules of rhetoric. When they do, however, the reader will usually find in the sentence some compensating merit, attained at the cost of the violation. Unless he is certain of doing as well, he will probably do best to follow the rules.

References: K&R2 Sec. 3.8
E. Dijkstra, ``Go To Statement Considered Harmful''
D.E. Knuth, ``Structured Programming with goto Statements''

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North