C++ goto Statements


August 18, 2022, Learn eTutorial
786

The goto statement in C++ programming is used to change the normal sequence of program execution by transferring control to another part of the program.

The syntax for the goto statements in C++


goto label;
... .. ...
... .. ...
... .. ...
label: 
statement;
... .. ...

 

The label seems to be an identifier in the above-given syntax. When the command goto label; is encountered, the program's control jumps to label: and will execute the code given below it.

Goto Statements

The fig shows the working of goto in C++

An example for goto statements

let us write a program that will calculate the average of numbers that is entered by the user.

suppose If the user enters a  number that is negative, it will surely ignore the number and will calculate the average number which was entered before it.


# include <iostream>
using namespace std;

int main()
{
    float num, average, sum = 0.0;
    int i, n;

    cout << "Maximum number of inputs: ";
    cin >> n;

    for(i = 1; i <= n; ++i)
    {
        cout << "Enter n" << i << ": ";
        cin >> num;
        
        if(num < 0.0)
        {
           // Control of the program move to jump:
            goto jump;
        } 
        sum += num;
    }
    
jump:
    average = sum / (i - 1);
    cout << "\nAverage = " << average;
    return 0;
}

Output:

Average = -nanMaximum number of inputs: 3
Enter n1: 1
Enter n2: 2
Enter n3: 3
Average = 2

Goto statements are optional in C++ programming, and it is generally recommended to avoid using them.

The Reason to Avoid the goto Statement

  • The goto statement allows you to jump to any part of a program, but it complicates and tangles the logic.
  • The goto statement is considered a harmful construct and bad programming practice in modern programming.
  • In most C++ programs, the goto statement can be replaced with break and continue statements.