C++ goto statement
The goto
statement in C++ is used to transfer control to a labeled statement in the same function. The basic syntax of the goto
statement is as follows:
1goto label; 2... 3label: statement;
The goto
statement transfers control to the labeled statement by jumping directly to the labeled statement. The labeled statement must be in the same function as the goto
statement. The goto
statement is generally considered to be a bad programming practice, as it can lead to code that is difficult to understand and maintain.
Let's take a look at three examples of the goto
statement in C++ and their output:
Example 1: Simple goto Statement in if Statement
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 int number = 1; 7 8 if (number == 1) 9 { 10 goto end; 11 } 12 cout << "This will not be executed." << endl; 13 14 end: 15 cout << "This will be executed." << endl; 16 17 return 0; 18}
In the above example, the goto
statement is used to transfer control to the labeled statement end
if the value of the number
variable is 1.
The output of the program will be:
1This will be executed.
Example 2: Simple goto Statement in if Statement
1 2#include <iostream> 3using namespace std; 4 5int main() 6{ 7 int number = 1; 8 9 top: 10 if (number == 1) 11 { 12 number++; 13 cout << "goto top:" << endl; 14 goto top; 15 } 16 17 cout << "number:" << number << endl; 18 19 return 0; 20}
The output of the program will be:
1goto top: 2number:2
Example 3: Simple goto Statement in Loops
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 for (int i = 0; i < 5; i++) 7 { 8 if (i == 2) 9 { 10 goto end; 11 } 12 cout << i << endl; 13 } 14 15 end: 16 cout << "This will be executed." << endl; 17 18 return 0; 19}
In the above example, the goto
statement is used to transfer control to the labeled statement end
if the value of the i
variable is 2. The output of the program will be:
10 21 3This will be executed.