How to Utilize the goto Statement in C++
-
Use the
goto
Statement Implement Program Control Flow Jumps in C++ -
Use the
goto
Statement to Implement Loop-Style Iteration in C++
This article will introduce how to utilize the goto
statement in C++.
Use the goto
Statement Implement Program Control Flow Jumps in C++
The goto
statement forces program control flow to jump to the line pointed by the label. Generally, any statement in C++ can be labeled using a special notation, which consists of an identifier followed by a colon. Usually, these label identifiers are available everywhere in the scope of the function. So, they can be referred to by goto
statements that are located before the label. The previous scope rule is different from the one for variables - that forces the variables to be declared before they are used by other statements.
Note though, goto
can’t jump forward into a scope and skip over variable declaration statements that have initializers, non-trivial constructor/destructors, or are non-scalar types. Otherwise, the compiler error is expected to be raised. In the following example, we search for the first appearance of the given string in the text, and once it is found, the loop is broken with the goto
statement to move control at the end of the program. As a result, the cout
statement indicating the failure message is skipped and only executed when no string matches the user passed string value.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
int main() {
string text(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit."
" Nam mollis felis eget diam fermentum, sed consequat justo pulvinar. ");
string search_query;
cout << "Enter a string to search: ";
cin >> search_query;
std::istringstream iss(text);
string word;
while (iss >> word) {
if (word == search_query) {
cout << "'" << search_query << "' - found in text" << endl;
goto END;
}
}
cout << "Could not find such string!" << endl;
END:
return EXIT_SUCCESS;
}
Alternatively, we can fulfill the previous example with a user input validation function that adds more robustness to the code in terms of fail-safe behavior. cin
member functions are utilized to implement input checking functionality and return the reference to the data that was read.
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
template <typename T>
T &validateInput(T &val) {
while (true) {
cout << "Enter a string to search: ";
if (cin >> val) {
break;
} else {
if (cin.eof()) exit(EXIT_SUCCESS);
cout << "Enter a string to search:\n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
return val;
}
int main() {
string text(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit."
" Nam mollis felis eget diam fermentum, sed consequat justo pulvinar. ");
string search_query;
validateInput(search_query);
std::istringstream iss(text);
string word;
while (iss >> word) {
if (word == search_query) {
cout << "'" << search_query << "' - found in text" << endl;
goto END;
}
}
cout << "Could not find such string!" << endl;
END:
return EXIT_SUCCESS;
}
Use the goto
Statement to Implement Loop-Style Iteration in C++
The goto
statement can be used to implement loop-like behavior, where the if
condition evaluates each iteration and determines whether the control will exit from the loop. Notice that we labeled the loop body with the names START
and END
. Basically, the iteration increments the score
variable until it is greater than 1000
. Thus, the iteration breaks when the value evaluates 1001
and at that point, the program moves to the line where the cout
statement is called.
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
int score = 1;
START:
if (score > 1000) goto EXIT;
score += 1;
goto START;
EXIT:
cout << "score: " << score << endl;
return EXIT_SUCCESS;
}
Output:
score: 1001
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook