C++ goto Statement

The goto statement in C++ is used to transfer the control of program to some other part of the program. A goto statement used as unconditional jump to alter the normal sequence of execution of a program.

Syntax of a goto statement in C++

goto label;
...
...
label:
... 
  • label : A label is an identifier followed by a colon(:) which identifies which marks the destination of the goto jump.
  • goto label: : When goto label; executes it transfers the control of program to the next statement label:.

C++ goto Statement Example Program

#include <iostream>
using namespace std;
 
int main(){

    int N, counter, sum=0;
    cout<< "Enter a positive number\n";
    cin >> N;
     
    for(counter=1; counter <= N; counter++){
        sum+= counter;
        /* If sum is greater than 50 goto
           statement will move control out of loop */
        if(sum > 50){
            cout << "Sum is > 50, terminating loop\n";
            // Using goto statement to terminate for loop
            goto label1;
        }
    }
    label1:
    if(counter > N)
        cout << "Sum of Integers from 1 to " << N <<" = "<< sum;
     
    return 0;
}
Output
Enter a positive number
25
Sum is > 50, terminating loop
Enter a positive number
8
Sum of Integers from 1 to 8 = 36

In above program, we first take an integer N as input from user using cin. We wan to find the sum of all numbers from 1 to N. We are using a for loop to iterate from i to N and adding the value of each number to variable sum. If becomes greater than 50 then we break for loop using a goto statement, which transfers control to the next statement after for loop body.


Disadvantages of goto statement
  • goto statement ignores nesting levels, and does not cause any automatic stack unwinding.
  • goto statement jumps must be limited to within same function. Cross function jumps are not allowed.
  • goto statement makes difficult to trace the control flow of program and reduces the readability of the program.
  • Use of goto statement is highly discouraged in modern programming languages.

Uses of goto Statement

The only place where goto statement is useful is to exit from a nested loops.

For Example :
for(...) {
 for(...){
  for(...){
   if(...){
    goto label1;
   }
  }
 }
}
label1:
statements;

In above example we cannot exit all three for loops at a time using break statement because break only terminate the inner loop from where break is executed.


Any program written in C++ language using goto statement can be re-written using break and continue statements.