c-plus-plus
  1. c-plus-plus-goto-statement

C++ Control Statement: Goto Statement

The C++ programming language provides the goto statement which allows the programmer to transfer the control of the program to a specific location within the code. However, the use of goto statement is often discouraged in modern programming practices because it can make the code hard to read and maintain.

Syntax

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

goto label;

//...

label: statement;

Here, label is a name given to a statement within the code and statement is the code that will be executed when the control jumps to that label.

Example

#include <iostream>
using namespace std;

int main() {
    int num;

    cout << "Enter a number between 1 and 5: ";
    cin >> num;

    if (num < 1 || num > 5) {
        cout << "Invalid number!";
        goto end;
    }

    cout << "You entered " << num;

    end:
    cout << "\nProgram ended.";
    return 0;
}

Output

If the user enters a number less than 1 or greater than 5:

Enter a number between 1 and 5: 6
Invalid number!
Program ended.

If the user enters a valid number between 1 and 5:

Enter a number between 1 and 5: 4
You entered 4
Program ended.

Explanation

In the above example, we are using the goto statement to jump to the end label when the user enters an invalid number. If the number is valid, we skip the goto statement and continue with the program flow.

Use

Although the use of goto statement is not recommended, it can be used in the following scenarios:

  • To jump out of multiple nested loops or switch statements.
  • To handle errors in functions where multiple return statements exist.

Important Points

  • The goto statement should be used sparingly.
  • It can make debugging and maintaining code difficult.
  • The label used should be unique and meaningful.

Summary

In C++, the goto statement allows the programmer to transfer the control of the program to a specific location within the code. However, it is not recommended to use goto statement as it can make the code hard to read and maintain. The label used should be unique and meaningful to ensure readability of the code.

Published on: