Sams Teach Yourself C++ in 21 Days

(singke) #1

The Roots of Looping:goto..........................................................................


In the primitive days of early computer science, programs were nasty, brutish, and short.
Loops consisted of a label, some statements, and a jump that went to the label.
In C++, a label is just a name followed by a colon (:). The label is placed to the left of a
legal C++ statement. A jump is accomplished by writing gotofollowed by the name of a
label. Listing 7.1 illustrates this primitive way of looping.

LISTING7.1 Looping with the Keyword goto
1: // Listing 7.1
2: // Looping with goto
3: #include <iostream>
4:
5: int main()
6: {
7: using namespace std;
8: int counter = 0; // initialize counter
9: loop:
10: counter ++; // top of the loop
11: cout << “counter: “ << counter << endl;
12: if (counter < 5) // test the value
13: goto loop; // jump to the top
14:
15: cout << “Complete. Counter: “ << counter << endl;
16: return 0;
17: }

counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
Complete. Counter: 5.
On line 8,counteris initialized to zero. A label called loopis on line 9, marking
the top of the loop. counteris incremented and its new value is printed on line


  1. The value of counteris tested on line 12. If the value is less than 5 , the ifstatement
    is trueand the gotostatement is executed. This causes program execution to jump back
    to the looplabel on line 9. The program continues looping until counteris equal to 5 ,at
    which time it “falls through” the loop and the final output is printed.


Why gotoIs Shunned ....................................................................................


As a rule, programmers avoid goto, and with good reason. gotostatements can cause a
jump to any location in your source code, backward or forward. The indiscriminate use

OUTPUT


176 Day 7


ANALYSIS
Free download pdf