How we change what others think, feel, believe and do
CHAPTER 8 : Language Usage
8.8 Using 'goto'
The unconditional branch has long been reviled in structured programming texts, and many programmers avoid it like the plague. It decreases readability and increases potential for error by breaking the structure and transferring execution to anywhere else within the function. It is a statement in two parts, the goto itself and the label, which can cause synchronization problems. Nevertheless, if it is to be used, there are some elements that should be considered.
8.8.1 Inserting around labels
If you are inserting code at the same point as the label, do you insert it before or after the label? If the label marks the beginning of a section of code, then the insertion is probably after it. If it marks the end of a section, then the insertion may be before it. This can be helped by a clear indication in the label name or the comment as to whether it marks the end or the beginning of a chunk of code:
8.8.2 Jump outwards
Jumping into compound statements is hazardous, as it disturbs the flow of the code, and is likely to result in problems such as jumping past some essential initialization. Bad examples include: jumping into or back and fore from the two parts of an if..else statement, jumping into switch statements and jumping into iteration statements.
By using the simple rule of never jumping into compound statements, some of the dangers of goto can be avoided.
A further constraint may be to not jump backwards. This prevents goto being used for looping, and will make the label easier to find (just look downwards).
8.8.3 Escaping deep nesting
A classic case where goto is often allowed is where it is necessary to escape from a deep level of nesting, typically for error handling (see 10.4.3).
Note that goto can be used to jump out of situations where break or continue, which can only jump out one level, could not be used.
In deciding if, when and where to use goto, balance its usefulness carefully against its hazards, and beware of emotional arguments based on unreasoned prejudice.
And the big