Control Flow
Goto Statement
Unconditional jump (and why to avoid it)
Interview: Understanding legacy code
Goto Statement
The goto statement transfers execution directly to a labeled statement within the same function. While generally discouraged in high-level code (it creates "spaghetti code"), it has legitimate use cases in C++ — particularly breaking out of deeply nested loops and error-handling in legacy C-style code.
Legitimate Use Cases
The Linux kernel and other high-performance C/C++ systems use goto extensively for cleanup-on-error patterns (jumping to a cleanup label at the end of a function). This predates C++ exceptions and RAII and achieves similar cleanup with minimal overhead.
Interview Corner
Q: Is goto ever acceptable in modern C++?
A: Yes, in limited scenarios. Breaking out of nested loops is the most common justification when refactoring to a function is impractical. The rule: goto is acceptable if it jumps forward only and doesn't jump across variable initializations. Modern C++ prefers RAII and exceptions for resource cleanup, making goto mostly obsolete.
Common Pitfalls
- Jumping over variable initialization: Jumping to a label that skips a variable's initialization is a compile error in C++ (unlike C).
- Backward jumps: Using goto to jump backwards creates loops that are much harder to follow than explicit loop constructs.
Best Practices
- Avoid goto in new C++ code. Use RAII, exceptions, or structured loops instead.
- If goto must be used, restrict to forward-only jumps with clear, descriptive label names like
cleanup:orerror_exit:.