goto Statement in C++
The goto statement is used to transfer the control of the program directly from one part of the program to another part.
It jumps to a specific location in the program using a label.
The goto statement is also known as a jump statement.
Syntax of goto Statement:
goto label_name;
label_name:
// code to be executed
How goto Statement Works?
Algo of goto Statement
- First, the program starts executing normally.
- When the goto statement is encountered, control jumps to the specified label.
- The statements between goto and the label are skipped.
- Execution continues from the labeled statement.
- The program then runs normally until it ends.
Note: Excessive use of the goto statement can make programs difficult to understand and debug. Modern programming mostly prefers loops and functions instead of goto.
Program 1: Skip Statements Using goto
#include <iostream>
using namespace std;
int main() {
cout << "Line 1" << endl;
goto skip;
cout << "Line 2" << endl;
cout << "Line 3" << endl;
skip:
cout << "Line 4";
return 0;
}
Output:
Line 1
Line 4
Explanation:
- First, "Line 1" is printed.
- The goto skip; statement transfers the control directly to the label skip:.
- Therefore, the statements "Line 2" and "Line 3" are skipped.
- Finally, "Line 4" is printed.
Program 2: Print Numbers Using goto
#include <iostream>
using namespace std;
int main() {
int i = 1;
start:
cout << i << " ";
i++;
if(i <= 5)
{
goto start;
}
return 0;
}
Output:
1 2 3 4 5
Explanation:
- The variable i is initialized with value 1.
- The label start: marks the jumping position.
- The value of i is printed.
- After printing, i++ increases the value by 1.
- If the condition (i <= 5) becomes true, control jumps back to start:.
- This process continues until the condition becomes false.
- Finally, the loop stops after printing numbers from 1 to 5.
Summary:
- goto statement is used to jump from one part of the program to another.
- It works with a label.
- Statements between goto and label can be skipped.
- Overuse of goto can make code confusing.
- Loops and functions are generally preferred over goto.
- The label name must be unique inside a function.