In this tutorial, you will learn about the goto statement in C++, how it works and why should it be avoided.
Contents
What is Goto statement?
The goto statement in C++ is also known as the jump statement. It is used to pass control to another section of the program. It always jumps to the supplied label.
It can be used to pass control from a deeply nested loop or switch case label to another.
Working of Goto statement
The first line instructs the compiler to move to or jump to the labeled statement. A label is a user-defined identifier that indicates the target statement in this case. The destination statement is the statement that comes immediately after ‘label‘ In the above syntax, the ‘label:’ can also exist before the ‘goto label’ statement.
Advantages and Disadvanatges of Goto statement
Advantages | Disadvantages |
---|---|
1: Using the goto command, you can change the typical sequence of program execution, allowing you to jump to any area of the program. | 1: The use of the goto statement is strongly discouraged because it complicates the program logic. 2: The usage of goto makes evaluating and verifying the correctness of programs (especially those including loops) extremely difficult. 3: Using break and continue statements, you can easily avoid using goto. |
Examples of goto statement
Example 1: goto statement
// The average of the numbers entered by the user is computed by this programme. // If the user enters a negative number, it ignores it and computes the average of the numbers entered before it. # include <iostream> using namespace std; int main() { float num, average, sum = 0.0; int i, n; cout << "Maximum number of inputs: "; cin >> n; for(i = 1; i <= n; ++i) { cout << "Enter n" << i << ": "; cin >> num; if(num < 0.0) { // Control of the program move to jump: goto jump; } sum += num; } jump: average = sum / (i - 1); cout << "\nAverage = " << average; return 0; }
Output:
Maximum number of inputs: 10
Enter n1: 2.3
Enter n2: 5.6
Enter n3: -5.6
Average = 3.95
Example 2: goto statement
#include <iostream> using namespace std; int main() { ineligible: cout<<"You are not eligible to vote!\n"; cout<<"Enter your age:\n"; int age; cin>>age; if (age < 18){ goto ineligible; } else { cout<<"You are eligible to vote!"; } }
Output:
You are not eligible to vote!
Enter your age:
16
You are not eligible to vote!
Enter your age:
7
You are not eligible to vote!
Enter your age:
22
You are eligible to vote!
goto statement in c++ goto statement in c++ goto statement in c++
You may like:
C++ Continue Statement with Example | C++ Programming
C++ Break Statement with Example | C++ Programming
C++ switch case statement with Example | C++ Programming
Pingback: Functions in C++ with Example | C++ Programming - Developers Dome
Pingback: C++ User-defined Function Types with Examples
Pingback: Friend Function and Friend Classes In C++ - Developers Dome