C++ goto Statement

Hi everyone, inside this article we will see about C++ goto Statement.

The “goto” statement in C++ is used to transfer control to another part of a program, bypassing any intermediate steps. It is used to jump from one location in the code to another.

The “goto” statement is considered as a dangerous feature of C++ as it can lead to the creation of code that is difficult to understand and maintain, and can also introduce bugs that are hard to track down.

Syntax & Explanation

It is defined using the following syntax:

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

In the above example, the “goto” statement transfers control to the line with the “label” in the code. The label must be followed by a colon and a statement. The statement can be any valid C++ statement, including another “goto” statement.

It is generally recommended to avoid the use of “goto” statements in C++, and to instead use structured control statements like “if-else”, “for”, “while”, and “do-while” to achieve the desired program flow.

Here, a pictorial representation of goto statement:

A Basic Program

Here’s a simple program in C++ that demonstrates the use of a goto statement:

#include <iostream>
using namespace std;

int main()
{
    ineligible:
        cout << "You are not eligible to vote!\n";
        cout << "Enter your age:\n";
        int age;
        cin >> age;
        if (age < 18)
        {
            goto ineligible;
        }
        else
        {
            cout << "You are eligible to vote!";
        }
  
  return 0;
}

The output of this program will be:

You are not eligible to vote!
Enter your age:
17
You are not eligible to vote!
Enter your age:
18
You are eligible to vote!

We hope this article helped you to understand about C++ goto Statement in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.