Introduction to C++ | goto Statement

C++ goto Statement

The goto statement in C++ is used to transfer control to a specific label in the program. It allows you to jump to another part of the code, making it possible to skip over certain sections or create loops. While the goto statement is available, it is generally discouraged as it can make the code less readable and harder to maintain.

What is the goto Statement?

The goto statement is used to transfer control to a labeled statement in the program. The labeled statement can be located anywhere in the function, and the program will jump to that point when the goto is executed.

Syntax of goto Statement

The syntax of the goto statement is as follows:

Syntax of goto


        goto label;
        ...
        label: statement;
                    

Example of goto in C++

Here is an example of using the goto statement in a program:

Code Example


        #include <iostream>
        using namespace std;
        
        int main() {
            int i = 0;
        
            start: // Label
            cout << "i = " << i << endl;
        
            i++;
        
            if (i < 5) {
                goto start;  // Jump back to the start label
            }
        
            return 0;
        }
                    

Output

i = 0
i = 1
i = 2
i = 3
i = 4

Explanation of Code

In the code above, the program starts with the label start. The program prints the value of i, increments it, and then checks if i is less than 5. If it is, the goto start; statement jumps back to the label start, repeating the process until i reaches 5. Once the condition is no longer true, the loop stops.

When to Use goto

The goto statement can be useful in specific situations, such as breaking out of deeply nested loops or for error handling. However, it is generally recommended to use other control flow statements like break, continue, or proper looping structures like while and for instead of goto.

Pro Tip:

💡 Pro Tip

While goto is available in C++, it should be used sparingly. Overuse of goto can make your code difficult to follow and maintain. In most cases, using structured loops and functions will make your code more readable and maintainable. Try to refactor your logic to avoid relying on goto unless absolutely necessary.