In this tutorial you will learn about the C++ goto statement and its application with practical example.
C++ goto statement
In C++, goto statement is used to alter the normal execution of a program and transfer control to a labeled statement in the same program. In a C++ program we can have multiple goto and label statements, the goto statement is followed by a label name. Label is an identifier, which can be any plain text and can be set anywhere in a C++ program above or below to goto statement. When a goto statement is encountered, compiler transfers the control to a label: specified with goto statement and begin execution from there.
Syntax:-
1 |
goto label; |
Program Structure:-
1 2 3 4 5 6 7 8 |
label1: ... ... goto label2; ... .. label2: ... |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> using namespace std; int main() { int age; cout<<"W3Adda - C++ goto Statement"; election: cout<<"\nEnter your age :"; cin>>age; if (age <= 17) { cout<<"\nYou are not eligible to vote."; goto election; } else { cout<<"You are eligible to vote."; } return 0; } |
Output:-