How to Utilize the goto Statement in C++?

The goto statement in C++ is a control flow statement that allows the users to move the control flow from one part to another part of the program. In this article, we will learn how to utilize the goto statement in C++.

Utilize the goto Statement in C++

In C++, the goto statement transfers the program’s control flow from one part to another. It allows the users to jump to another part of the program while skipping the current part. Although it is generally advised to use structured control flow statements for readability and maintainability, there are many scenarios where the goto statement can be useful. Following is the syntax for goto:

Syntax

#include <iostream>

int main() {
// ... code before goto

goto label; // Jump to the label

// ... code that will be skipped by the goto

label:
// ... code after the label

return 0;
}

C++ Program to Utilize the goto Statement

The following program demonstrates how we can utilize the goto statement to break out of multiple nested loops

C++
// C++ Program to Utilize the goto Statement
#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            if (i == 1 && j == 2) {
                // Exit both loops
                goto endLoops;  
            }
            cout << i << ", " << j << endl;
        }
    }

endLoops:
    cout << "Exited the nested loops." << endl;

    return 0;
}

Output
0, 0
0, 1
0, 2
1, 0
1, 1
Exited the nested loops.

Time Complexity: O(1), as goto is used to terminate the loop iterations
Auxiliary Space: O(1)

Utilize goto for error handling

The following program illustrates how goto statement can be used for error handling in order to avoid unnecessary calculations:

C++
// C++ Program to utilize goto for error handling
#include <iostream>
#include <limits>
using namespace std;

int main() {
    double numerator = 10.0;
    double denominator = 0.0; 
    double result;

    if (denominator == 0) {
        // Jump to cleanup if denominator is 0
        goto cleanup;
    }

    // Perform the division
    result = numerator / denominator;
    cout << "Result: " << result << endl;

cleanup:
    cerr << "Error: Division by zero is not allowed." << endl;
    cout << "Program has finished executing." << endl;

    return 0;
}


Output

ERROR!
Error: Division by zero is not allowed.
Program has finished executing.

Time Complexity: O(1)
Auxiliary Space: O(1)