MASIGNASUKAv102
6510051498749449419

C++ goto Statement - Learn With AVRK

Add Comments
Tuesday, August 31, 2021

Goto Statement in C++ Language

Goto statement is also known as jump statement. It is used to transfer control to another part of the program. It jumps to the specified label unconditionally.

It can be used to transfer control from deep nested loops or switch case labels.

Syntax of goto Statement

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

In the syntax above, label is an identifier. when goto label is encountered, the program's control jumps to label and executes the block of code below it.

Loading...

C++ goto Statement Example -
Let's look at a simple example of a goto statement in C++.
#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:
15
You are not eligible to vote!
Enter your age:
10
You are not eligible to vote!
Enter your age:
20
You are eligible to vote!

Note:- You can write any C++ program without the use of goto statements and it is generally considered a good idea not to use them.

Reason to Avoid goto Statement

The goto statement gives the power to jump to any part of the program, but makes the logic of the program complicated and tangled.

In modern programming, the goto statement is considered a harmful construct and a bad programming practice.

The goto statement can be replaced in most of C++ program with the use of break and continue statements.

Also check out this : C++ Continue Statement - Learn With AVRK
Learn With AVRK

Learn With AVRK