c++

C++ goto statement

In this article, we are going to learn about goto statement.

In C++ programming, goto statement is used for altering the normal sequence of program execution by transferring control to some different part of the program.

The syntax of the goto statement in C++ is:

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

In above syntax, label is an identifier. When goto label; is encountered, the control of program went to label: and starts executing the code.


Example :

// Program to calculate the sum and average of positive numbers
// If user enters negative number by mistake, it ignores the number and
// calculates the average of all numbers entered before it.

# include <iostream>

using namespace std;

int main() {
    float number, avg, sum = 0.0;
    int a, n;

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

    for(a = 1; a <= n; ++a) {

        cout << "Enter n" << a << ": ";
        cin >> number;
        cout << endl;

        if(number < 0.0) {
            // Control of the program move to jump:
            goto jump;
        }
        sum += number;
    }
    jump:
        avg = sum / (a - 1);
        cout << "\navg = " << avg;
        return 0;
    }

Output :

Maximum number of inputs: 10
Enter n1: -5.6
Enter n2: 2.4
Enter n3: 3.6
avg= 3.0

We can write a C++ program without using goto Statement.

Note : Using goto Statement in our program is a bad programming practice.


Why we should avoid using GOTO STATEMENT in our program?

  1. The goto statement helps us to jump to any part of program easily without reading whole code but, makes the working of the program complex .
  2. Nowadays programming, GOTO statement is considered a bad programming practice.
  3. The GOTO statement can be easily replaced in most of C++ programs with the use of break and continue statements.