Goto Statement in Cpp

Hello Learners,

In the previous article, we discussed C++ break statement. Today, we will discuss the Goto statement in Cpp in this article.

The jump statement is another name for the Goto statement. It transfers control to another section of the program. It always goes to the label specified.

What is Goto Statement in Cpp

In C++, the goto statement is an unconditional jump statement used to transfer a program’s control. It allows the execution flow of the program to jump to a specific location within the function.

Syntax for Goto Statement in Cpp

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

Related: Practice your coding skills on star pattern problems

Working of Goto Statement in Cpp

There can be any number of goto and label statements in a program; a label name follows the goto statement; whenever a goto statement is encountered, the program’s control jumps to the label specified in the goto statement.

Working of Goto Statement In Cpp
  • Save

Example of Goto statement in Cpp

#include <iostream>

using namespace std;

int main(){
    
    int num; cout<<"Enter a number: "; cin>>num;
    
     if (num % 2==0){

        goto print;

    }
    else {

        cout<<"Odd Number";
    
    }
 
    print:
    
    cout<<"Even Number";
    
    return 0;

}

Output

Enter a number: 42
Even Number

Explanation

When the control flow encounters goto with label name print, then the control flow will jump to print, and it gets executed, and so it prints “Even Number”.

Related: Learn C++ effectively from this free course

Why not use Goto Statement?

Because early programming languages, such as FORTRAN and early versions of BASIC, lacked structured statements such as while, programmers were forced to create loops using goto statements.

The issue with using goto statements is that it is very easy to develop program logic that is difficult to understand, even by the original author of the code. If the goto point is above the goto call, it is easy to become trapped in an infinite loop.

How can one avoid the goto statement?

Goto is not unavoidable, and it can be avoided. Break and continue statements can be used to avoid using the goto statement. Also, we have different loops like for loop & while loop. So, basically, we don’t have any solid reason of using it.

Related: Click here for Best IDE for C++ programming

Conclusion

So, this was all about Goto statement in Cpp. We hope you found the article helpful. If you have any doubts or found any error, you can comment below. You can also mail us at: cpptopics@techoutflow.com. The next discussion will be on Functions in Cpp.

Till then, stay tuned

Share via
Copy link
Powered by Social Snap