What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

What is goto statement in C++? (Why to Avoid It?)

  • May 17, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Anubhav Agarwal
What is goto statement in C++? (Why to Avoid It?)

We will study today the goto statement in C++ with examples. What is it actually, how to use it, when to avoid it, and what are its better alternatives in C++? However, note that using the goto statement is generally not recommended for new programmers.

What is the goto statement in C++?

The goto statement in C++ is an unconditional jump statement to transfer the program's execution to another part of it using a label.  The main use case of goto is when it is impossible to transfer control to the desired location using other statements.

Here is a general syntax for the goto statement:

goto label;
... .. ...
... .. ...
... .. ...
label: 
statement;
... .. ...

 

You define your goto statement wherever you want to, When 'goto label;' is encountered, the control of the program jumps to 'label:' and executes the code below it. Like many jump statements, goto is also a jump statement to jump from in between the flow of execution to some other part of your program and do some manipulations accordingly.

C++ goto Statement Examples 

 In the 1st example, we will use the goto statement with if else conditions. We will check whether the number provided by the user is even or odd and here we will use the goto statement only to perform this task. Below is the code as shown:

// C program to check if a number is
// even or not using goto statement
#include<stdio.h>
  
// function to check even or not
void checkEvenOrNot(int num)
{
    if (num % 2 == 0)
        // jump to even
        goto even; 
    else
        // jump to odd
        goto odd; 
  
even:
    printf("%d is even", num);
    // return if even
    return; 
odd:
    printf("%d is odd", num);
}
  
int main() {
    int num = 26;
    checkEvenOrNot(num);
    return 0;
}

 

Output:

26 is even

 

Note that in the C programming language, the goto statement has fewer restrictions and can enter the scope of any variable other than a variable-length array or variably-modified pointer.

 In the second example, we will use the goto statement to print Numbers sequentially from 1 to 10. Here is the code:

// Welcome to Favtutor
// C program to print numbers
// from 1 to 10 using goto statement
#include<stdio.h>

// function to print numbers from 1 to 10
void printNumbers()
{
	int n = 1;
label:
	printf("%d ",n);
	n++;
	if (n <= 10)
		goto label;
}

// Driver program to test above function
int main() {
	printNumbers();
	return 0;
}

 

Output:

1 2 3 4 5 6 7 8 9 10

 

If the transfer of control exits the scope of any automatic variables (e.g. by jumping backward to a point before the declarations of such variables or by jumping forward out of a compound statement where the variables are scoped), the destructors are called for all variables whose scope was exited, in the order opposite to the order of their construction.

The goto statement can also be used in the struct in C++ as shown below:

// Welcome to Favtutor
#include<iostream>
 
struct Object {
    // non-trivial destructor
    ~Object() { std::cout << "d"; }
};
 
struct Trivial {
    double d1;
    double d2;
}; // trivial ctor and dtor
 
int main()
{
    int a = 10;
 
    // loop using goto
label:
    Object obj;
    std::cout << a << " ";
    a = a - 2;
 
    if (a != 0) {
        goto label;  // jumps out of scope of obj, calls obj destructor
    }
    std::cout << '\n';
 
    // goto can be used to leave a multi-level loop easily
    for (int x = 0; x < 3; x++) {
        for (int y = 0; y < 3; y++) {
            std::cout << "(" << x << ";" << y << ") " << '\n';
            if (x + y >= 3) {
                goto endloop;
            }
        }
    }
endloop:
    std::cout << '\n';
 
    goto label2; // jumps into the scope of n and t
    int n; // no initializer
    Trivial t; // trivial ctor/dtor, no initializer
//  int x = 1; // error: has initializer
//  Object obj2; // error: non-trivial dtor
label2:
 
    {
        Object obj3;
        goto label3; // jumps forward, out of scope of obj3
    }
label3: 
    std::cout << '\n';
}

 

Output:

10 d8 d6 d4 d2
(0;0) 
(0;1) 
(0;2) 
(1;0) 
(1;1) 
(1;2) 
 
d
d

 

Can I use the goto statement in C++? 

Yes, the goto statement can be used in C++ but it is generally advised to avoid it can make your code harder to maintain. It makes the program logic very complex, and analyzing tasks and verifying the correctness of programs (particularly those involving loops) becomes difficult.

The goto non-linear control flow is very difficult to understand for some programmers to take over. There is also a higher chance that you might introduce new bugs in the code.

The older use cases were to break out of nested loops or error handling. Also, if your software has some older code, you must at least understand how it works. New programmers can use other mainstream control flow statements like if, while, for, and functions instead of goto. 

Conclusion

So, we studied the goto statement in C++ in this simple guide. But remember that the use of goto statements is not a good practice. Congratulations on getting this far! Now give yourself a pat on the back. Good job!

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Anubhav Agarwal
I'm a research-oriented engaged in various technologies and a technical content writer. Being a coder myself, going through the documentation to provide optimized solutions as technical content is what I always look for.