×

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

strcat() vs strncat() in C++

In this tutorial, we will explore about strcat() and strncat() in the most usable language C++. We will also look at the difference between them. strcat() C++ is a computer language with...

4 minutes read.

Input Iterators in C++

What are input iterators? Input iterators are used in sequence for carrying out input operations where each value is read-only. It is pointed by the iterator and further incremented. All the iterators...

4 minutes read.

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function....

3 minutes read.

C++ Program to Implement Shell Sort

    C++ Program to Implement Shell Sort shell sort is basically an Insertion Sort variant. In the insertion sort, we only transfer elements ahead of one location. Many movements are involved...

2 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

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.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

How to create the Processes with Fork in C++

 In this article, we are going to explain the different methods that help us to create processes with a fork(). There are two methods to do so. These methods are...

2 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

C++ Virtual Function

A virtual function is such function which is declared inside the base class and redefined by the derive class. C++ uses a virtual keyword to make a function as a virtual function. The virtual...

1 minute read.

C++ STL (Standard Template Library)

Introduction C++ is a flexible type and general proposed programming language. So we need a standard library that supports C++. C++ STL (Standard Template Library) is a collection of templates that...

6 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

Copy elision in C++

The Copy Omission is another name for the Copy Elision. One of the several compiler optimization techniques is copy elision. It prevents items from being copied inadvertently. This Copy Elision approach...

3 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.