Example of goto in C or C++


The goto statement is a jump statement that allows the program control to jump from goto to a label. Using the goto statement is frowned upon as it makes the program convoluted and hard to understand.

The following is the syntax of goto statement.

goto label;
.
.
.
label: statements;

A program that demonstrates the goto statement in C++ is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int main () {
   int i = 1;
   while(1) {
      cout<< i <<"\n";
      if(i == 10)
      goto OUT;
      i++;
   }
   OUT: cout<<"Out of the while loop";
   return 0;
}

Output

The output of the above program is as follows.

1
2
3
4
5
6
7
8
9
10
Out of the while loop

Now, let us understand the above program.

A while loop is used in the above program. In each pass of the while loop, the value of i is displayed. Then, if statement is used to check if the value of i is 10. If so, then goto statement is used to leave the while loop. Otherwise, i is incremented by 1.

The label used with the goto statement is OUT and it leads the program control out of the while loop. Then "Out of the while loop" is displayed. The code snippet for this is given as follows.

int i = 1;
while(1) {
   cout<< i <<"\n";
   if(i == 10)
   goto OUT;
   i++;
}
OUT: cout<<"Out of the while loop";

Updated on: 26-Jun-2020

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements