Goto statement in C++

The C++ goto statement is used to jump directly to that part of the program to which it is being called.  Every goto statement is associated with the label which takes them to part of the program for which they are called. The label statements can be written anywhere in the program it is not necessary to use them before or after the goto statement.

Syntax

goto label_name;
.
.
.
label_name:

Flowchart of goto Statement

Note: The goto statement makes it difficult to understand the flow of the program therefore it is avoided to use it in a program.

Example of goto

Below is the program to demonstrate the goto statement:

C++




// C++ program to demonstrate the
// goto statement
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    int n = 4;
 
    if (n % 2 == 0)
        goto label1;
    else
        goto label2;
 
label1:
    cout << "Even" << endl;
    return 0;
 
label2:
    cout << "Odd" << endl;
}


Output

Even

Explanation:
The above program is used to check whether the number is even or odd if the number pressed by the user says it is 4 so the condition is met by the if statement and control go to label1 and label1 prints that the number is even. Here it is not necessary to write a label statement after the goto statement we can write it before goto statement also it will work fine.



Jump statements in C++

Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function.

Similar Reads

Types of Jump Statements in C++

In C++,  there is four jump statement...

continue in C++

The C++ continue statement is used to execute other parts of the loop while skipping some parts declared inside the condition, rather than terminating the loop, it continues to execute the next iteration of the same loop. It is used with a decision-making statement which must be present inside the loop....

break in C++

...

return in C++

The C++ break statement is used to terminate the whole loop if the condition is met. Unlike the continue statement after the condition is met, it breaks the loop and the remaining part of the loop is not executed....

Goto statement in C++

...

Contact Us