C++ Programming/Programming Languages/C++/Code/Keywords/goto

The   keyword is discouraged as it makes it difficult to follow the program logic, this way inducing to errors. The   statement causes the current thread of execution to jump to the specified label.


 * Syntax

In some rare cases, the   statement allows to write uncluttered code, for example, when handling multiple exit points leading to the cleanup code at a function exit (and neither exception handling or object destructors are better options). Except in those rare cases, the use of unconditional jumps is a frequent symptom of a complicated design, as the presence of many levels of nested statements.

In exceptional cases, like heavy optimization, a programmer may need more control over code behavior; a   allows the programmer to specify that execution flow jumps directly and unconditionally to a desired label. A label is the name given to a label statement elsewhere in the function.

A   can, for example, be used to break out of two nested loops. This example breaks after replacing the first encountered non-zero element with zero.

Although simple, they quickly lead to illegible and unmaintainable code.

is much less understandable than the equivalent:

Gotos are typically used in functions where performance is critical or in the output of machine-generated code (like a parser generated by yacc.)

The   statement should almost always be avoided, but there are rare cases where it enhances the readability of code. One such case is an "error section".

Example

This construct avoids hassling with the origin of the error and is cleaner than an equivalent construct with control structures. It is thus less error prone.