next up previous
Next: for Loop Up: Overview of C++ Previous: Activity

goto Statement

The goto statement causes your program to jump to a different location, rather than execute the next statement in sequence. The format of the goto statement is


\begin{emph}
{\bf goto} statement label
 \end{emph}

A statement label is named just as variables. A statement label cannot have the same name as C++ keywords (see table 2.3), a C++ function, or another variable in the program. If you use a goto statement, there must be a statement label elsewhere in the program that the goto branches to. Execution then continues at the statement with the statement label. Follow all statement labels with a colon (:) so C++ knows they are labels and doesn't get them confused with variables. Example of goto and statement label is shown below

Example

/* This program to illustrate the use of goto, statement labels and counters */
#include <iostream.h>
main()
int i; i=0 // define i as 0
again: // this is a statement label
cout << "$\backslash$t keeps repeating $\backslash$n";
cout << "$\backslash$t over and over $\backslash$n";
if(i==10) goto stop;
i=i+1 /* this is a counter which makes i=i+1 every time it reaches this point this can be presented also by or i++*/

goto again; //it cause the program to goto statement label again
stop: // this is a statement label
return 0;
}


next up previous
Next: for Loop Up: Overview of C++ Previous: Activity
Yousef Haik
2/23/1998