C++ Goto Statement
The goto statement in C++ allows jumping to a labeled statement in the same function. While it can simplify certain scenarios, its misuse may lead to spaghetti code, so use it carefully.
1. Basic Goto Example
This example demonstrates jumping to a label using goto.
C++
Example: Basic goto statement
#include <iostream>
using namespace std;
int main() {
int i = 1;
if(i == 1) {
goto skip;
}
cout << "This will be skipped" << endl;
skip:
cout << "Jumped to label" << endl;
return 0;
}
2. Common Mistakes
Using goto to jump across functions or skipping variable initialization is invalid. Overuse can make code unreadable and hard to maintain.
Conclusion
C++ goto statement allows jumping to labeled statements within the same function. It should be used sparingly and only when other control structures are less convenient.
Codecrown