C++ goto statement and its usage

In this tutorial, we will learn about the C++ goto statement and its usage in detail.

Before proceeding to its implementation, let us understand the key characteristics of the goto statement and its usage. The goto statement :

  • is a jump statement.
  • is also known as an unconditional jump statement.
  • transfers the control of the program from one place to another in a program with the use of labels.
  • contains labels that indicate where it transfers the control of the program.
  • expresses itself in two ways namely, write first the label followed by the goto statement and vice versa.
  • alters the normal flow of control of the program execution.
  • follows the label name with a semicolon to indicate where it gives the control of the program.
  • is difficult to use when labels increase. It makes the program difficult to understand.
  • can be replaced by the break and continue statements. It reduces the complexity of the program.
  • becomes a bad program structure when the program contains various logic and is complex. In these cases, it is better to avoid the use of the goto statement.

Syntax of goto statement in C++

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

Program to illustrate C++ goto statement and its usage:

#include <iostream>
using namespace std;
int main() 
{ 
    int n1;
    cout<<"Enter a number either positive or negative"<<endl;
    cin>>n1;
    if (n1 > 0) // jump to positive label
        goto positive;  
    else  // jump to negative label
        goto negative;  
    positive: 
        cout << n1 << " is positive";
        return 0;
    negative: 
        cout << n1 << " is negative";  
        return 0; 
}

Output:

Enter a number either positive or negative
10
10 is positive
Enter a number either positive or negative
-5
-5 is negative

This program shows how to check a number whether it is positive or negative. For this, we use an if-else statement with a condition in it. If the if condition satisfies, the control transfers to the positive label. If it fails, then the control transfers to the negative label. Finally, the statement in the respective labels executes and the program terminates with the above output on the terminal.

I hope this post was helpful to learn the basics of the C++ goto statement and its usage. Thanks for reading!

Recommended Posts:
Break and Continue in C++

Keywords in C++

Leave a Reply

Your email address will not be published. Required fields are marked *