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:
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:
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:
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:
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.
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!