×

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples.

What is the goto statement in C++?

In C++, the goto statement is used to transfer control to a labelled statement inside the same function. It provides an unconditional hop between program points by avoiding the conventional control flow.

Syntax:

It has the following syntax:

goto label;

...

label:

    // Code to execute after jumping

When to use the goto statement?

  • Sometimes, goto is useful for breaking out of extremely nested loops.
  • One of its rare applications is error handling in legacy code.

Key Features of the goto statement:

Several key features of the goto statement in C++ are as follows:

  1. Unconditional Jump: Transfers control within the same function to a specified statement.
  2. Label Definition: A colon (:) must come after a label has been defined.
  3. Avoids Code Execution: Intermediate code blocks can be avoided, but doing so may cause important activities to be missed.
  4. Limited Scope: The label must be in the same function as goto and cannot move between functions.
  5. Legacy Use: It is mostly seen in older C++ projects, although generally discouraged in modern development.

Key points:

Several key points of the goto statement in C++ are as follows:

  • Syntax: It uses the goto keyword after a label name.
  • Readability Issues: It makes code more difficult to comprehend and maintain (spaghetti code).
  • Better Alternatives: Loops (for, while), break, continue, and function calls are preferred.
  • Error Handling Use: It is occasionally used in error handling when several cleanup actions are needed.
  • Performance Considerations: Goto typically does not improve performance and can make debugging challenging.

Pseudo code:

BEGIN 

    PRINT "Before goto"

    GOTO label  // Jump to the label


    PRINT "This line will be skipped"


LABEL:

    PRINT "After goto"

END

Algorithm:

  1. Start the program.
  2. Print “Before goto”.
  3. Execute goto label statement, which transfers control to the defined label.
  4. Skip any statements between goto and the label.
  5. Reach the label, and execute the code after it.
  6. Print “After goto”.
  7. End the program.

Example 1:

Let us take an example to illustrate the goto statement in C++.

#include <iostream>

using namespace std;

int main() {

    cout << "Before goto" << endl;

    goto jump;  // Jumps to the 'jump' label

    cout << "This will be skipped" << endl;

    jump:

    cout << "After goto" << endl;

    return 0;

}

Output:

Before goto

After goto

Despite being a feature of C++, the goto function should often be avoided unless it is absolutely required for readability and velocity.

Example 2:

Let us take another C++ code using the goto statement to exit loops.

#include <iostream>

using namespace std;

int main() {

    // Nested loops

    for (int i = 1; i <= 5; i++) {

        for (int j = 1; j <= 5; j++) {

            cout << "i = " << i << ", j = " << j << endl;

            // Condition to exit both loops using goto

            if (i == 3 && j == 2) {

                goto exit_loop;  // Jump to exit point

            }

        }

    }

exit_loop:  // Label where control jumps

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

    return 0;

}

Output:

i = 1, j = 1

i = 1, j = 2

i = 1, j = 3

i = 1, j = 4

i = 1, j = 5

i = 2, j = 1

i = 2, j = 2

i = 2, j = 3

i = 2, j = 4

i = 2, j = 5

i = 3, j = 1

i = 3, j = 2

Exited the nested loops.

Explanation:

  • Two nested for loops are used at the beginning of the program.
  • In each repetition, the values of i and j are printed.
  • The goto exit_loop is run when i == 3 and j == 2.
  • Jumps to exit_loop: label and skips all subsequent iterations.
  • The program terminates when the message “Exited the nested loops.” is displayed.

Why to avoid the goto statement?

  • This makes it more challenging to debug and understand code.
  • It could lead to “spaghetti code”, which is difficult to follow.
  • Modern C++ offers better alternatives, such as functions and loops.

Alternative using loops:

Instead of the goto statement, we can use the break or continue statement in C++.

#include <iostream>

using namespace std;

int main() {

for (int i = 0; i < 5; i++)

{

    if (i == 3)

        break;  // Exits the loop when i == 3

    cout << i << " ";

}

}

Output:

0 1 2

Conclusion:

In C++, the goto statement is used to unconditionally access a labelled statement inside the same function. It can be helpful in some situations, such as repairing errors in ancient code or breaking out of deeply nested loops, even though its use is generally discouraged due to readability and maintainability issues. Using goto too much can result in “spaghetti code”, which makes the program harder to debug and comprehend. Better control flow strategies are offered by more modern alternatives, such as loops, functions, break, continue, and exception handling. Consequently, even though goto is still a feature of C++, it should only be used in extreme circumstances and only when no other options are available.


Related Topics

Handling multiple clients on the Server with multithreading using Socket Programming in C or C++

To understand this guide completely, the reader is assumed to be familiar with the foundations of server and client models and socket programming. If one wants to create any scalable...

7 minutes read.

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of...

3 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

C++ String Concatenation

C++ String Concatenation In this section, we will learn about C ++ String Concatenation, what it does, how it works, and will also see its programs. What is the String Concatenation? The + operator...

3 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

C++ | C Plus Plus While loop

In this article, we will discuss the C++ while loop with its syntax, use, key features, key points, pseudo code, and examples. What is the While Loop? The “while loop” is a...

4 minutes read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.