The goto Statement: A (Very) Brief History
The goto statement was cast into disfavor with the publication of a paper titled "Go To Statement Considered Harmful," by Edsger W. Dijkstra, in 1968. At that particular time in programming history, a debate was raging over the issue of structured programming. Unfortunately, less attention was focused on the overall issues raised by structured programming than on a relatively small detail: whether particular statements, such as go to (now usually the goto keyword), should be present in modern programming languages. As is too often the case, many people took Dijkstra's advice and ran to the extreme, concluding that all uses of goto were bad and that use of goto should be avoided at all costs.
The problem with using goto isn't the keyword itself-rather, it's the use of goto in inappropriate places. The goto statement can be a useful tool in structuring program flow and can be used to write more expressive code than that resulting from other branching and iteration mechanisms. One such example isthe "loop-and-a-half" problem, as coined by Dijkstra. Here is the traditional flow of the loop-and-a-half problem in pseudocode: -
loop read in a value if value == sentinel then exit process the value end loop
The exit from the loop is accomplished only by the execution of the exit statement in the middle of the loop. This loop/exit/end loop cycle, however, can be quite disturbing to some people who, acting on the notion that all uses of goto are evil, would write this code as follows: -
read in a value while value != sentinel process the value read in a value end while
Unfortunately, as Eric S. Roberts of Stanford University points out, this second approach has two major drawbacks. First, it requires the duplication of the statement(s) required to read in a value. Any time you duplicate code, this results in an obvious maintenance problem in that any change to one statement must be made to the other. The second problem is more subtle and probably more damning. The key to writing solid code that's easy to understand, and therefore maintain, is to write code that reads in a natural manner. In any noncode description of what this code is attempting to do, one would describe the solution as follows: First, I need to read in a value. If that value is a sentinel, I stop. If not, I process that value and continue to the next value. Therefore, it's the code omitting the exit statement that's actually counterintuitive because that approach reverses the natural way of thinking about the problem. Now, let's look at some situations in which a goto statement can result in the best way to structure control flow.