E.11. The Unconditional Branch: goto
E 11 The Unconditional Branch goto
Throughout the text we have stressed the importance of using structured programming techniques to build reliable software that is easy to debug, maintain and modify. In some cases, performance is more important than strict adherence to structured-programming techniques. In these cases, some unstructured programming techniques may be used. For example, we can use break to terminate execution of a repetition structure before the loop-continuation condition becomes false. This saves unnecessary repetitions of the loop if the task is completed before loop termination.
Another instance of unstructured programming is the goto statementan unconditional branch. The result of the goto statement is a change in the flow of control of the program to the first statement after the label specified in the goto statement. A label is an identifier followed by a colon. A label must appear in the same function as the goto statement that refers to it. Figure E.7 uses goto statements to loop 10 times and print the counter value each time. After initializing count to 1, the program tests count to determine whether it is greater than 10. (The label start is skipped, because labels do not perform any action.) If so, control is transferred from the goto to the first statement after the label end. Otherwise, count is printed and incremented, and control is transferred from the goto to the first statement after the label start.
Figure E.7. Using goto.
(This item is displayed on pages 1261 - 1262 in the print version)
1 // Fig. E.7: figE_07.cpp 2 // Using goto. 3 #include 4 using std::cout; 5 using std::endl; 6 7 #include 8 using std::left; 9 using std::setw; 10 11 int main() 12 { 13 int count = 1; 14 15 start: // label 16 // goto end when count exceeds 10 17 if ( count > 10 ) 18 goto end; 19 20 cout << setw( 2 ) << left << count; 21 ++count; 22 23 // goto start on line 17 24 goto start; 25 26 end: // label 27 cout << endl; 28 29 return 0; 30 } // end main
|
In Chapters 45, we stated that only three control structures are required to write any programsequence, selection and repetition. When the rules of structured programming are followed, it is possible to create deeply nested control structures from which it is difficult to escape efficiently. Some programmers use goto statements in such situations as a quick exit from a deeply nested structure. This eliminates the need to test multiple conditions to escape from a control structure.
Performance Tip E.2
The goto statement can be used to exit deeply nested control structures efficiently but can make code more difficult to read and maintain. |
Error-Prevention Tip E.1
The goto statement should be used only in performance-oriented applications. The goto statement is unstructured and can lead to programs that are more difficult to debug, maintain and modify. |