C++ goto Statement — Syntax and Alternatives | Tutorials Logic
What is goto?
The goto statement transfers control unconditionally to a labeled statement within the same function. It is one of the oldest control flow mechanisms inherited from C.
#include <iostream>
using namespace std;
int main() {
int i = 0;
loop: // label
if (i < 5) {
cout << i << " ";
i++;
goto loop; // jump back to label
}
cout << endl; // 0 1 2 3 4
// goto to skip code
int x = 10;
if (x > 5) goto skip;
cout << "This won't print" << endl;
skip:
cout << "Jumped here with goto" << endl;
return 0;
}
// Note: goto cannot jump over variable initializations
// int y = 5;
// goto label;
// int z = 10; // ERROR: jump over initialization
// label: ...;
#include <iostream>
using namespace std;
// The ONLY somewhat acceptable use of goto in C++:
// breaking out of deeply nested loops
// (even then, prefer a helper function)
bool findInMatrix(int matrix[][3], int rows, int target) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == target) {
return true; // BETTER: use return instead of goto
}
}
}
return false;
}
int main() {
int matrix[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
// Structured approach - no goto needed
if (findInMatrix(matrix, 3, 5)) {
cout << "Found 5 in matrix" << endl;
}
// Simple loop - use for/while, not goto
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
cout << endl;
return 0;
}
Key Takeaways
- goto transfers control to a labeled statement - it is generally considered bad practice.
- goto can only jump within the same function - it cannot jump between functions.
- The main valid use case for goto in C++ is breaking out of deeply nested loops.
- Modern C++ alternatives to goto: break with labels, exceptions, or refactoring into functions.
- goto can skip variable initialization - this causes a compile error in C++.
- Most coding standards (Google, LLVM, etc.) prohibit or strongly discourage goto.
Level Up Your C plus plus Skills
Master C plus plus with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Related C++ Topics