The structured program theorem proved that the goto statement is not necessary to write programs; some combination of the three programming constructs of sequence, selection/choice, and repetition/iteration are sufficient for any computation that can be performed by a Turing machine, with the caveat that code duplication and additional variables may need to be introduced.[1]

In the past there was considerable debate in academia and industry on the merits of the use of goto statements. Use of goto was formerly common, but since the advent of structured programming in the 1960s and 1970s its use has declined significantly. The primary criticism is that code that uses goto statements is harder to understand than alternative constructions. Goto remains in use in certain common usage patterns, but alternatives are generally used if available. Debates over its (more limited) uses continue in academia and software industry circles.

The goto statement is often combined with the if statement to cause a conditional transfer of control.

IFconditionTHENgotolabel

Programming languages impose different restrictions with respect to the destination of a goto statement. For example, the C programming language does not permit a jump to a label contained within another function,[3] however jumps within a single call chain are possible using the setjmp/longjmp functions.

At the pre-ALGOL meeting held in 1959 Heinz Zemanek explicitly threw doubt on the necessity for GOTO statements; at the time no one paid attention to his remark, including Edsger W. Dijkstra, who later became the iconic opponent of GOTO.[4] The 1970s and 1980s saw a decline in the use of GOTO statements in favor of the "structured programming" paradigm, with goto criticized as leading to "unmaintainable spaghetti code" (see below). Some programming style coding standards, for example the GNU Pascal Coding Standards, recommend against the use of GOTO statements.[5] The Böhm-Jacopini proof (1966) did not settle the question of whether to adopt structured programming for software development, partly because the construction was more likely to obscure a program than to improve it because its application requires the introduction of additional local variables.[6] It did, however, spark a prominent debate among computer scientists, educators, language designers and application programmers that saw a slow but steady shift away from the formerly ubiquitous use of the GOTO. Probably the most famous criticism of GOTO is a 1968 letter by Edsger Dijkstra called Go To Statement Considered Harmful.[4][7] In that letter Dijkstra argued that unrestricted GOTO statements should be abolished from higher-level languages because they complicated the task of analyzing and verifying the correctness of programs (particularly those involving loops). The letter itself sparked a debate, including a "'GOTO Considered Harmful' Considered Harmful" letter[8] sent to Communications of the ACM (CACM) in March 1987, as well as further replies by other people, including Dijkstra's On a Somewhat Disappointing Correspondence.[9]

An alternative viewpoint is presented in Donald Knuth's Structured Programming with go to Statements, which analyzes many common programming tasks and finds that in some of them GOTO is the optimal language construct to use.[10] In their quasi-standard book on the C programming language, Dennis Ritchie and Brian Kernighan warn that goto is "infinitely abusable", but also suggest that it could be used for end-of-function error handlers and for multi-level breaks from loops.[11] These two patterns can be found in numerous subsequent books on C by other authors;[12][13][14][15] a 2007 introductory textbook notes that the error handling pattern is a way to work around the "lack of built-in exception handling within the C language".[12] Other programmers, including Linux Kernel designer and coder Linus Torvalds or software engineer and book author Steve McConnell, also object to Dijkstra's point of view, stating that GOTOs can be a useful language feature, improving program speed, size and code clearness, but only when used in a sensible way by a comparably sensible programmer.[16][17] According to computer science professor John Regehr, in 2013, there were about 100,000 instances of goto in the Linux kernel code.[18]

Other academics took a more extreme viewpoint and argued that even instructions like break and return from the middle of loops are bad practice as they are not needed in the Böhm-Jacopini result, and thus advocated that loops should have a single exit point.[19] For instance, Bertrand Meyer wrote in his 2009 textbook that instructions like break and continue "are just the old goto in sheep's clothing".[20] A slightly modified form of the Böhm-Jacopini result allows however the avoidance of additional variables in structured programming, as long as multi-level breaks from loops are allowed.[21] Because some languages like C don't allow multi-level breaks via their break keyword, some textbooks advise the programmer to use goto in such circumstances.[15] The MISRA C 2004 standard bans goto, continue, as well as multiple return and break statements.[22] The 2012 edition of the MISRA C standard downgraded the prohibition on goto from "required" to "advisory" status; the 2012 edition has an additional, mandatory rule that prohibits only backward, but not forward jumps with goto.[23][24]

FORTRAN introduced structured programming constructs in 1978, and in successive revisions the relatively loose semantic rules governing the allowable use of goto were tightened; the "extended range" in which a programmer could use a GOTO to enter and leave a still-executing DO loop was removed from the language in 1978,[25] and by 1995 several forms of Fortran GOTO, including the Computed GOTO and the Assigned GOTO, had been deleted.[26] Some widely used modern programming languages such as Java and Python lack the GOTO statement – see language support – though most provide some means of breaking out of a selection, or either breaking out of or moving on to the next step of an iteration. The viewpoint that disturbing the control flow in code is undesirable may be seen in the design of some programming languages, for instance Ada[27] visually emphasizes label definitions using angle brackets.

Programming style, like writing style, is somewhat of an art and cannot be codified by inflexible rules, although discussions about style often seem to center exclusively around such rules. In the case of the goto statement, it has long been observed that unfettered use of goto's quickly leads to unmaintainable spaghetti code. However, a simple, unthinking ban on the goto statement does not necessarily lead immediately to beautiful programming: an unstructured programmer is just as capable of constructing a Byzantine tangle without using any goto's (perhaps substituting oddly-nested loops and Boolean control variables, instead). Many programmers adopt a moderate stance: goto's are usually to be avoided, but are acceptable in a few well-constrained situations, if necessary: as multi-level break statements, to coalesce common actions inside a switch statement, or to centralize cleanup tasks in a function with several error returns. (...) Blindly avoiding certain constructs or following rules without understanding them can lead to just as many problems as the rules were supposed to avert. Furthermore, many opinions on programming style are just that: opinions. They may be strongly argued and strongly felt, they may be backed up by solid-seeming evidence and arguments, but the opposing opinions may be just as strongly felt, supported, and argued. It's usually futile to get dragged into "style wars", because on certain issues, opponents can never seem to agree, or agree to disagree, or stop arguing.

While overall usage of gotos has been declining, there are still situations in some languages where a goto provides the shortest and most straightforward way to express a program's logic (while it is possible to express the same logic without gotos, the equivalent code will be longer and often more difficult to understand). In other languages, there are structured alternatives, notably exceptions and tail calls.

Implementing multi-level break and continue if not directly supported in the language; this is a common idiom in C.[15] Although Java reserves the goto keyword, it doesn't actually implement it. Instead, Java implements labelled break and labelled continue statements.[32] According to the Java documentation, the use of gotos for multi-level breaks was the most common (90%) use of gotos in C.[33] Java was not the first language to take this approach—forbidding goto, but providing multi-level breaks— the BLISS programming language (more precisely the BLISS-11 version thereof) preceded it in this respect.[34]:960–965

Surrogates for single-level break or continue (retry) statements when the potential introduction of additional loops could incorrectly affect the control flow. This practice has been observed in Netbsd code.[35]

These uses are relatively common in C, but much less common in C++ or other languages with higher-level features.[36] However, throwing and catching an exception inside a function can be extraordinarily inefficient in some languages; a prime example is Objective-C, where a goto is a much faster alternative.[38]

Another use of goto statements is to modify poorly factored legacy code, where avoiding a goto would require extensive refactoring or code duplication. For example, given a large function where only certain code is of interest, a goto statement allows one to jump to or from only the relevant code, without otherwise modifying the function. This usage is considered code smell, but finds occasional use.

These new language mechanism replace equivalent flows which previously would have been written using gotos and ifs. Multi-way branching replaces the "computed goto" in which the instruction to jump to is determined dynamically (conditionally).

In practice, a strict adherence to the basic three-structure template of structured programming yields highly nested code, due to inability to exit a structured unit prematurely, and a combinatorial explosion with quite complex program state data to handle all possible conditions.

Two solutions have been generally adopted: a way to exit a structured unit prematurely, and more generally exceptions – in both cases these go up the structure, returning control to enclosing blocks or functions, but do not jump to arbitrary code locations. These are analogous to the use of a return statement in non-terminal position – not strictly structured, due to early exit, but a mild relaxation of the strictures of structured programming. In C, break and continue allow one to terminate a loop or continue to the next iteration, without requiring an extra while or if statement. In some languages multi-level breaks are also possible. For handling exceptional situations, specialized exception handling constructs were added, such as try/catch/finally in Java.

The throw-catch exception handling mechanisms can also be easily abused to create non-transparent control structures, just like goto can be abused.[39]

In a paper delivered to the ACM conference in Seattle in 1977, Guy L. Steele summarized the debate over the GOTO and structured programming, and observed that procedure calls in the tail position of a procedure can be most optimally treated as a direct transfer of control to the called procedure, typically eliminating unnecessary stack manipulation operations.[40] Since such "tail calls" are very common in Lisp, a language where procedure calls are ubiquitous, this form of optimization considerably reduces the cost of a procedure call compared to the GOTO used in other languages. Steele argued that poorly implemented procedure calls had led to an artificial perception that the GOTO was cheap compared to the procedure call. Steele further argued that "in general procedure calls may be usefully thought of as GOTO statements which also pass parameters, and can be uniformly coded as machine code JUMP instructions", with the machine code stack manipulation instructions "considered an optimization (rather than vice versa!)".[40] Steele cited evidence that well optimized numerical algorithms in Lisp could execute faster than code produced by then-available commercial Fortran compilers because the cost of a procedure call in Lisp was much lower. In Scheme, a Lisp dialect developed by Steele with Gerald Jay Sussman, tail call optimization is mandatory.[41]

Although Steele's paper did not introduce much that was new to computer science, at least as it was practised at MIT, it brought to light the scope for procedure call optimization, which made the modularity-promoting qualities of procedures into a more credible alternative to the then-common coding habits of large monolithic procedures with complex internal control structures and extensive state data. In particular, the tail call optimizations discussed by Steele turned the procedure into a credible way of implementing iteration through single tail recursion (tail recursion calling the same function). Further, tail call optimization allows mutual recursion of unbounded depth, assuming tail calls – this allows transfer of control, as in finite state machines, which otherwise is generally accomplished with goto statements.

Coroutines are a more radical relaxation of structured programming, allowing not only multiple exit points (as in returns in non-tail position), but also multiple entry points, similar to goto statements. Coroutines are more restricted than goto, as they can only resume a currently running coroutine at specified points – continuing after a yield – rather than jumping to an arbitrary point in the code. A limited form of coroutines are generators, which are sufficient for some purposes. Even more limited are closures – subroutines which maintain state (via static variables), but not execution position. A combination of state variables and structured control, notably an overall switch statement, can allow a subroutine to resume execution at an arbitrary point on subsequent calls, and is a structured alternative to goto statements in the absence of coroutines; this is a common idiom in C, for example.

A continuation is similar to a GOTO in that it transfers control from an arbitrary point in the program to a previously marked point. A continuation is more flexible than GOTO in those languages that support it, because it can transfer control out of the current function, something that a GOTO cannot do in most structured programming languages. In those language implementations that maintain stack frames for storage of local variables and function arguments, executing a continuation involves adjusting the program's call stack in addition to a jump. The longjmp function of the C programming language is an example of an escape continuation that may be used to escape the current context to a surrounding one. The Common Lisp GO operator also has this stack unwinding property, despite the construct being lexically scoped, as the label to be jumped to can be referenced from a closure.

In Scheme, continuations can even move control from an outer context to an inner one if desired. This almost limitless control over what code is executed next makes complex control structures such as coroutines and cooperative multitasking relatively easy to write.[42]

In FORTRAN, a computed GOTO jumps to one of several labels in a list, based on the value of an expression. An example is goto (20,30,40) i. The equivalent construct in C is the switch statement and in newer Fortran a CASE statement is the recommend syntactical alternative.[43]BASIC has the ON ... GOTO construct that achieves the same goal.[44]

Fortran also had an assigned goto variant that transfers control to a statement label (line number) which is stored in (assigned to) an integer variable. Jumping to an integer variable that had not been ASSIGNed to was unfortunately possible, and was a major source of bugs involving assigned gotos.[45] The Fortran assign statement only allows a constant (existing) line number to be assigned to the integer variable. However, it was possible to accidentally treat this variable as an integer thereafter, for example increment it, resulting in unspecified behavior at goto time. The following code demonstrates the behavior of the goto i when line i is unspecified:[46]

Several C compilers implement two non-standard C/C++ extensions relating to gotos originally introduced by gcc.[47][48] The GNU extension allows the address of a label inside the current function to be obtained as a void* using the unary, prefix label value operator&&. The goto instruction is also extended to allow jumping to an arbitrary void* expression. This C extension is referred to as a computed goto in documentation of the C compilers that support it; its semantics are a superset of Fortran's assigned goto, because it allows arbitrary pointer expressions as the goto target, while Fortran's assigned goto doesn't allow arbitrary expressions as jump target.[49] As with the standard goto in C, the GNU C extension allows the target of the computed goto to reside only in the current function. Attempting to jump outside the current function results in unspecified behavior.[49]

Some variants of BASIC also support a computed GOTO in the sense used in GNU C, i.e. in which the target can be any line number, not just one from a list. For example, in MTS BASIC one could write GOTO i*1000 to jump to the line numbered 1000 times the value of a variable i (which might represent a selected menu option, for example).[50]

Up to the 1985 ANSI COBOL standard had the ALTER verb which could be used to change the destination of an existing GO TO, which had to be in a paragraph by itself.[51] The feature, which allowed polymorphism, was frequently condemned and seldom used.[52]

In Perl, there is a variant of the goto statement that is not a traditional GOTO statement at all. It takes a function name and transfers control by effectively substituting one function call for another (a tail call): the new function will not return to the GOTO, but instead to the place from which the original function was called.[53]

There are several programming languages that do not support GOTO by default. By using GOTO emulation, it is still possible to use GOTO in these programming languages, albeit with some restrictions. One can emulate GOTO in Java,[54] JavaScript,[55] and Python.[56][57]

PL/I has the data type LABEL, which can be used to implement both the "assigned goto" and the "computed goto." PL/I allows branches out of the current block. A calling procedure can pass a label as an argument to a called procedure which can then exit with a branch.

Many languages support the goto statement, and many do not. In Java, goto is a reserved word, but is unusable, although the compiled file.class generates GOTOs and LABELs.[58][59] Python does not have support for goto, although there are several joke modules that provide it.[56][57] In PHP there was no native support for goto until version 5.3 (libraries were available to emulate its functionality).[60]C# has goto. It also makes case and default statements labels, whose scope is the enclosing switch statement; goto case or goto default is often used to replace explicit "fall-through", which C# disallows.

Most languages that have goto statements call it that, but in the early days of computing, other names were used. For example, in MAD the TRANSFER TO statement was used.[61]

C has goto, and it is commonly used in various idioms, as discussed above.

^ANSI X3.9-1978. American National Standard – Programming Language FORTRAN. American National Standards Institute. Also known as ISO 1539-1980, informally known as FORTRAN 77

^ISO/IEC 1539-1:1997. Information technology – Programming languages – Fortran – Part 1: Base language. Informally known as Fortran 95. There are a further two parts to this standard. Part 1 has been formally adopted by ANSI.

^"The Java Language Specification, Third Edition". The keywords const and goto are reserved, even though they are not currently used. This may allow a Java compiler to produce better error messages if these C++ keywords incorrectly appear in programs.

^"The Java Language Specification, Third Edition". Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break (§14.15) or continue (§14.16) statements appearing anywhere within the labeled statement.