Why is goto Bad Programming Practice in C++?

(Image taken from https://xkcd.com/)

The goto statement in C++ (and many other languages) is generally considered bad programming practice. Here are some reasons why:

  • Breaks Structured Programming Principles: Modern C++ embraces structured programming, which focuses on control structures like sequences, selections (if-else, switch), and iterations (loops). goto disrupts this flow, leading to a tangled mess of jumps that are difficult to reason about.
  • Reduced Readability and Maintainability (Spaghetti Code): Excessive use of goto can lead to “spaghetti code,” where the program’s flow is difficult to trace, making the code harder to understand, debug, and maintain. Spaghetti Code: https://www.geeksforgeeks.org/software-engineering/spaghetti-code/
  • Increased Complexity: The ability to jump to anywhere within a function using goto can drastically increase the complexity of the code, making it difficult for humans to mentally model the program’s execution.
  • Potential for Undefined Behavior and Bugs: Careless use of goto can lead to undefined behavior, especially when jumping into the middle of a variable’s scope, potentially skipping initialization or destructor calls.
  • Difficulty with Optimization: Unstructured jumps caused by goto can make it harder for compilers to optimize the code effectively.
  • Better Alternatives Exist: Most situations where a goto might seem tempting can be handled more elegantly using C++’s standard control structures, like forwhileif-elseswitchbreakcontinue, and exceptions. 

Take a look at this Stack Overflow post that shows a student’s program that used goto: https://cplusplus.com/forum/beginner/210844/