Section 6.12. The goto Statement


6.12. The goto Statement

A goto statement provides an unconditional jump from the goto to a labeled statement in the same function.

Use of gotos has been discouraged since the late 1960s. gotos make it difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.



The syntactic form of a goto statement is

      goto label; 

where label is an identifier that identifies a labeled statement. A labeled statement is any statement that is preceded by an identifier followed by a colon:

      end: return; // labeled statement, may be target of a goto 

The identifier that forms the label may be used only as the target of a goto. For this reason, label identifiers may be the same as variable names or other identifiers in the program without interfering with other uses of those identifiers. The goto and the labeled statement to which it transfers control must be in the same function.

A goto may not jump forward over a variable definition:

      // ...      goto end;      int ix = 10; // error: goto bypasses declaration statement  end:      // error: code here could use ix but the goto bypassed its declaration      ix = 42; 

If definitions are needed between a goto and its corresponding label, the definitions must be enclosed in a block:

          // ...          goto end; // ok: jumps to a point where ix is not defined          {             int ix = 10;             // ... code using ix          }      end: // ix no longer visible here 

A jump backward over an already executed definition is okay. Why? Jumping over an unexecuted definition would mean that a variable could be used even though it was never defined. Jumping back to a point before a variable is defined destroys the variable and constructs it again:

      // backward jump over declaration statement ok        begin:          int sz = get_size();          if (sz <= 0) {                goto begin;          } 

Note that sz is destroyed when the goto executes and is defined and initialized anew when control jumps back to begin:.

Exercises Section 6.12

Exercise 6.22:

The last example in this section that jumped back to begin could be better written using a loop. Rewrite the code to eliminate the goto.




C++ Primer
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2006
Pages: 223
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net