In this lesson, you will learn about another Jump Statement in C++, the goto statement, with examples to better understand the topic.
In C++, The goto Statement changes how a program runs and transfers control to a different statement inside the same program. A goto statement causes the compiler to move control to the label indicated by the “goto” statement and start execution there.
Basic Syntax
goto label1; ... Label1:
The goto statement is not required in every C++ application, and it is generally recommended to avoid using it.
The statement against the goto Statement
The “goto” statement allows users to jump to any location inside a program but complicates and muddles the program’s logic. The “goto” statement is viewed as a destructive construct and poor programming practice in contemporary programming.
Example
#include <iostream>
using namespace std;
int main() {
int number;
startAgain:
cout << "\nGuess the number:";
cin >> number;
if ((number >= 155) && (number <= 200)) {
cout << "\nYou won.";
goto startAgain;
} else {
cout << "You lose.";
}
return 0;
}
Output
Guess the number:156 You won. Guess the number:154 You lose.
An identifier startAgain is a label in the above example. The program’s control jumps to label: startAgain and runs the code there when goto “startAgain” is encountered. The condition becomes true at if ((number >= 155) && (number <= 200)) when the user enters 156 and prints “You won”. Again program found the label startAgain and asked the user to prompt the input.
This concludes the C++ goto Statement lesson. The next lesson will teach about functions in C++.