Looping with the keyword goto in C++

By: Lakshmi Emailed: 1643 times Printed: 2109 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

In the primitive days of early computer science, programs were nasty, brutish, and short. Loops consisted of a label, some statements, and a jump.

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. The following C++ program illustrates this.

Looping with the keyword goto.

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 Is Shunned

goto has received some rotten press lately, and it's well deserved. 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." Because of this, computer science teachers have spent the past 20 years drumming one lesson into the heads of their students: "Never, ever, ever use goto! It is evil!"

To avoid the use of goto, more sophisticated, tightly controlled looping commands have been introduced: for, while, and do...while. Using these makes programs that are more easily understood, and goto is generally avoided, but one might argue that the case has been a bit overstated. Like any tool, carefully used and in the right hands, goto can be a useful construct, and the ANSI committee decided to keep it in the language because it has its legitimate uses. But as they say, kids, don't try this at home.

The goto Statement

To use the goto statement, you write goto followed by a label name. This causes an unconditioned jump to the label. Example

if (value > 10)     goto end;if (value < 10)     goto end;cout << "value is Â10!";end:cout << "done";

 


WARNING: Use of goto is almost always a sign of bad design. The best advice is to avoid using it. In 10 years of programming, I've needed it only once.

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Lakshmi
Exporting a Certificate Authenticating Your Public Key example using keytool in Java
while and do-while example in Java
Common SQL Commands
Data Access Technologies in Java
perror() Function - example program in C
Struts-GUI and Struts Console
Variable-length Argument Lists sample program in C
#if, #elif, #ifndef, #ifdef in C (Conditional Inclusion)
Use ImageButtonBean for Image based Form Submits in Struts
break and continue loops in C
Arguments - Call by Value in C
Using command-line arguments in C++
How to handle Exceptions in C++
Gauge sample program in J2ME
What is Reflection? - getConstructors(), getFields(), and getMethods()

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Using Comments in a C++ Program
Using cout in C++
Using peek() and putback() with cin in C++
Calculating total based on the given quantity and price in C++
Demonstration of Prefix and Postfix operators in C++
Classes with Other Classes as Member Data in C++
Escape Sequences for Nonprintable Characters in C++
Demonstrating global and local variables in C++
Returning values from a function in C++
C++ Recursion function explained using Fibonacci series
Tutorial on Classes and Members in C++
Constructors and Destructors in C++
Where to Put Class Declarations and Method Definitions in C++
Tutorial on Inline Implementation in C++
Looping with the keyword goto in C++
Most Emailed Articles (in C++)
Returning values from a function in C++
while (1) Loops in C++
Using Comments in a C++ Program
Public versus Private members in C++
The indirection operator (*) - dereference operator.
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Specifying default values to function parameters in C++
continue and break statements in C++
const Pointers in C++
Sorting an array of Strings in C++
Advanced if Statements in C++
while Loops in C++
Dot (.) vs Arrow (->) to access data members in C++
Stray or Dangling Pointers in C++