🎯 C++ goto Statement – Jump Around with Labels
The goto statement in C++ lets you jump to any labeled part of your program — like teleporting! 🛸
But warning: it can make your code messy and confusing if overused. Use it only when necessary.
🧠 Syntax of goto
goto label;
// ...
label:
// code to run
You define a label (with a colon), and goto jumps right there.
🔧 Example: goto in Action
#include <iostream>
using namespace std;
int main() {
int number = 0;
cout << "Enter a positive number: ";
cin >> number;
if (number <= 0) {
goto retry;
}
cout << "You entered: " << number << endl;
return 0;
retry:
cout << "Oops! Number must be positive!" << endl;
⚠️ When to Use goto?
- To break out of deeply nested loops (though
breakis often better) - To jump to error handling code in rare cases
Note: Overusing goto can lead to spaghetti code 🍝. So use it only when there’s no cleaner option!