Labeled Statements

 < Day Day Up > 



click to expand
Figure 6-7: goto Statement Diagram

There are three types of labeled statements: case, default, and identifier. You have seen the case and default labeled statements used in the switch statement. In this section I will discuss the identifier labeled statement.

A statement can be preceded with an identifier label which consists of the label’s name and a colon as shown in figure 6-7. The only use of such labeled statements is with the goto statement

goto Statement

The goto statement performs an unconditional jump either forward or backward in source code to a labeled statement. The range of the jump is within the current function. In other words, you can’t jump out of a function into another function, or back to the calling function, using a goto statement. But then you wouldn’t want to do that anyway! The following example shows a goto statement in action:

Listing 6.29: labeled statement

start example
1  int count = 0; 2 3  start: cout<<"This is the start!"<<endl; 4 5  if(count++ < 3) 6      goto start; 7 8  cout<<"All done!"<<endl;
end example

In this example line 3 is labeled with the identifier start:. The if statement will evaluate count and, if it is less than three, will execute the goto statement on line 6. This code can be rewritten without a goto statement by using a while loop as in the following example:

Listing 6.30: gotoless code

start example
1  int count = 0; 2 3  while(count++ < 3) 4      cout<<"This is the start!"<<endl; 5 6  cout<<"All done!"<<endl;
end example

Advice on Using Goto

If you must use a goto statement keep the jump within eye sight on the same page of code.



 < Day Day Up > 



C++ for Artists. The Art, Philosophy, and Science of Object-Oriented Programming
C++ For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504028
EAN: 2147483647
Year: 2003
Pages: 340
Authors: Rick Miller

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