| < Day Day Up > |
|
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
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
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;
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
1 int count = 0; 2 3 while(count++ < 3) 4 cout<<"This is the start!"<<endl; 5 6 cout<<"All done!"<<endl;
If you must use a goto statement keep the jump within eye sight on the same page of code.
| < Day Day Up > |
|