C++ Goto Statement

The C++ goto statement is also known as jump statement which performs an unconditional jump to a specified label. It is used to transfer control to the other part of the program.

The goto statement requires a label for operation. (A label is a valid identifier followed by a colon.) Furthermore, the label must be in the same function as the goto that uses it-you cannot jump between functions.

Syntax

The general form of the goto statement is

goto label;
..
..
label:

where label is any valid label either before or after goto.

Example

Let's see the simple example of goto statement in C++.

snippet
#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!";   
      }       
}
Output
You are not eligible to vote! Enter your age: 16 You are not eligible to vote! Enter your age: 7 You are not eligible to vote! Enter your age: 22 You are eligible to vote!
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +