C++ goto Statement
The goto statement allows control to be unconditionally transferred to a labeled statement within the same function.
Note: The use of the goto statement is discouraged in any programming language because it makes the program's control flow difficult to trace, making the program hard to understand and modify. Any program that uses a goto statement can be rewritten to avoid using it.
Syntax
The syntax for the goto statement in C++:
goto label;
..
.
label: statement;
Here, label is an identifier that identifies the labeled statement, which can be any plain text except for C++ keywords. The labeled statement can be any statement placed after the identifier and a colon (:).
Flowchart
Example
Example
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration
int a = 10;
// do loop execution
LOOP:do
{
if( a == 15)
{
// Skip the iteration
a = a + 1;
goto LOOP;
}
cout << "Value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19
A good use of the goto statement is to exit deeply nested routines. For example, consider the following code snippet:
for(...) {
for(...) {
while(...) {
if(...) goto stop;
.
.
.
}
}
}
stop:
cout << "Error in program.\n";
Eliminating goto would require executing some additional tests. A simple break statement would not work here because it would only exit the innermost loop.