< previous page page_112 next page >

Page 112
In C++, a label is just a name followed by a colon (:). The label is placed to the left of a legal C++ statement, and a jump is accomplished by writing goto followed by the label name. Listing 8.1 illustrates this.
LISTING 8.1 LOOPING WITH THE KEYWORDgoto

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:    // Listing 8.1
2:    // Looping with goto
3:
4:    #include <iostream.h>
5:
6:    int main()
7:    {
8:           int counter = 0;      // initialize counter
9:    loop:  counter++;           // top of the loop
10:          cout < counter:  < counter < \n;
11:          if (counter < 5)            // test the value
12:              goto loop;               // jump to the top
13:
14:          cout < Complete. counter:  < counter < .\n;
15:          return 0;
16:   }

Output:
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
Complete. counter: 5
Analysis: On line 8, counter is initialized to 0. The label loop is on line 9, marking the top of the loop. Counter is incremented, and its new value is printed. The value of counter is tested on line 11. If it is less than 5, the if statement is true and the goto statement is executed. This causes program execution to jump back to line 9. The program continues looping until counter is equal to 5, at which time it falls through the loop and the final output is printed.
Why goto Isn't Used
goto is generally not used in C++, and for good reason. goto statements can cause a jump to any location in your source code, backward or forward. The indiscriminate use of goto statements has caused tangled, miserable, impossible-to-read programs known as spaghetti code.
To avoid the use of goto, more sophisticated, tightly controlled looping commands have been introduced: for, while, and dowhile. Using these commands makes programs that are more easily understood, and goto is generally avoided.

 
< previous page page_112 next page >

If you like this book, buy it!