Goto

Gotois astatementfound in many computerprogramming languages.  It performs aone-way transferof control to another line of code; in contrast afunction callnormally returns control.  The jumped-to locations are usually identified usinglabels, though some languages useline numbers. At themachine codelevel, agotois a form ofbranch or jump statement, in some cases combined with a stack adjustment. Many languages support thegotostatement, and many do not (see§ language support).
Thestructured program theoremproved that thegotostatement is not necessary to write programs that can be expressed asflow charts; some combination of the three programming constructs of sequence, selection/choice, and repetition/iteration are sufficient for any computation that can be performed by aTuring machine, with the caveat thatcode duplicationand additional variables may need to be introduced.
The use of goto was formerly common, but since the advent ofstructured programmingin the 1960s and 1970s, its use has declined significantly. It remains in use in certaincommon usage patterns, butalternativesare generally used if available. In the past, there was considerable debate in academia and industry on the merits of the use of goto statements. The primarycriticismis that code that uses goto statements is harder to understand than alternative constructions. Debates over its (more limited) uses continue in academia and software industry circles.
gotolabel
Thegotostatement is often combined with theif statementto cause a conditional transfer of control.
IFconditionTHENgotolabel
Programming languages impose different restrictions with respect to the destination of agotostatement. For example, theC programming languagedoes not permit a jump to a label contained within another function,however jumps within a single call chain are possible using thesetjmp/longjmpfunctions.
At thepre-ALGOLmeeting held in 1959,Heinz Zemanekexplicitly cast doubt on the necessity of GOTO statements; at the time no onepaid attention to his remark, includingEdsger W. Dijkstra, who later became the iconic opponent of GOTO.The 1970s and 1980s saw a decline in the use of GOTO statements in favor of thestructured programmingparadigm, with GOTO criticized as leading to unmaintainablespaghetti code. Someprogramming stylecoding standards, for example the GNU Pascal Coding Standards, recommend against the use of GOTO statements.TheBö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.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".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" lettersent toCommunications of theACM(CACM) in March 1987, as well as further replies by other people, including Dijkstra'sOn a Somewhat Disappointing Correspondence.
An alternative viewpoint is presented inDonald Knuth'sStructured Programming with go to Statements, which analyzes many common programming tasks and finds that in some of them GOTO is the optimallanguage constructto use.InThe C Programming Language,Brian KernighanandDennis Ritchiewarn thatgotois "infinitely abusable", but also suggest that it could be used for end-of-function error handlers and for multi-level breaks from loops.These two patterns can be found in numerous subsequent books on C by other authors;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".Other programmers, includingLinuxkernel designer and coderLinus Torvaldsor software engineer and book authorSteve McConnell, also object to Dijkstra's point of view, stating that GOTOs can be a useful language feature, improving program speed, size and code clarity, but only when used in a sensible way by a comparably sensible programmer.According to computer science professorJohn Regehr, in 2013, there were about 100,000 instances of goto in the Linux kernel code.
Other academics took a more extreme viewpoint and argued that even instructions likebreakandreturnfrom 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.For instance,Bertrand Meyerwrote in his 2009 textbook that instructions likebreakandcontinue"are just the oldgotoin sheep's clothing".A slightly modified form of the Böhm–Jacopini result, however, allows the avoidance of additional variables in structured programming, as long as multi-level breaks from loops are allowed.Because some languages like C don't allow multi-level breaks via theirbreakkeyword, some textbooks advise the programmer to usegotoin such circumstances.TheMISRA C2004 standard bansgoto,continue, as well as multiplereturnandbreakstatements.The 2012 edition of the MISRA C standard downgraded the prohibition ongotofrom "required" to "advisory" status; the 2012 edition has an additional, mandatory rule that prohibits only backward, but not forward jumps withgoto.
FORTRANintroduced 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 leave and re-enter a still-executing DO loop was removed from the language in 1978,and by 1995 several forms of Fortran GOTO, including the Computed GOTO and the Assigned GOTO, had been deleted.Some widely used modern programming languages such asJavaandPythonlack the GOTO statement – seelanguage support– though most provide some means of breaking out of a selection, or eitherbreakingout of ormovingon 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 instanceAdavisually emphasizes label definitions usingangle brackets.
Entry 17.10 in comp.lang.c FAQ listaddresses the issue of GOTO use directly, stating
While overall usage of goto 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.
Situations in which goto is often useful include:
These uses are relatively common in C, but much less common in C++ or other languages with higher-level features.However, throwing and catching an exception inside a function can be extraordinarily inefficient in some languages; a prime example isObjective-C, where a goto is a much faster alternative.
Another use of goto statements is to modify poorly factoredlegacy code, where avoiding a goto would require extensiverefactoringorcode 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 consideredcode smell,but finds occasional use.
The modern notion ofsubroutinewas invented byDavid Wheelerwhen programming theEDSAC. To implement a call and return on a machine without a subroutine call instruction, he used a special pattern of self-modifying code, known as aWheeler jump.This resulted in the ability to structure programs using well-nested executions of routines drawn from a library. This would not have been possible using onlygoto, since the target code, being drawn from the library, would not know where to jump back to.
Later, high-level languages such asPascalwere designed around support forstructured programming, which generalized fromsubroutines(also known as procedures or functions) towards
furthercontrol structuressuch as:
These new language mechanisms replaced equivalent flows which previously would have been written usinggotos andifs.  Multi-way branching replaces the "computed goto" in which the instruction to jump to is determined dynamically (conditionally).
Under certain conditions it is possible to eliminate local goto statements of legacy programs by replacing them with multilevel loop exit statements.
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 acombinatorial explosionwith 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 generallyexceptions– in both cases these goupthe 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,breakandcontinueallow one toterminate a looporcontinue to the next iteration, without requiring an extrawhileorifstatement. In some languages multi-level breaks are also possible. For handling exceptional situations, specializedexception handlingconstructs were added, such astry/catch/finallyin Java.
The throw-catch exception handling mechanisms can also be easily abused to create non-transparent control structures, just like goto can be abused.
In a paper delivered to the ACM conference in Seattle in 1977,Guy L. Steelesummarized 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.Since such "tail calls" are very common inLisp, 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 asmachine codeJUMP instructions", with the machine code stack manipulation instructions "considered an optimization (rather than vice versa!)".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.  InScheme, a Lisp dialect developed by Steele withGerald Jay Sussman, tail call optimization is mandatory.
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 singletail recursion(tail recursion calling the same function). Further, tail call optimization allowsmutual recursionof unbounded depth, assuming tail calls – this allows transfer of control, as infinite-state machines, which otherwise is generally accomplished with goto statements.
Coroutinesare 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 onlyresumea 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 aregenerators, which are sufficient for some purposes. Even more limited areclosures– subroutines which maintain state (viastatic 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.
Acontinuationis 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'scall stackin addition to a jump. Thelongjmpfunction of theC programming languageis an example of an escape continuation that may be used to escape the current context to a surrounding one.  TheCommon LispGO operator also has this stack unwinding property, despite the construct beinglexically scoped, as the label to be jumped to can be referenced from aclosure.
InScheme, 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.
In non-procedural paradigms, goto is less relevant or completely absent. One of the main alternatives ismessage passing, which is of particular importance inconcurrent computing,interprocess communication, andobject oriented programming. In these cases, the individual components do not have arbitrary transfer of control, but the overall control may be scheduled in complex ways, such as viapreemption. The influential languagesSimulaandSmalltalkwere among the first to introduce the concepts of messages and objects.  Byencapsulatingstate data,object-oriented programmingreduced software complexity to interactions (messages) between objects.
There are a number of different language constructs under the class ofgotostatements.
InFortran, acomputedGOTOjumps to one of several labels in a list, based on the value of an expression. An example isgoto (20,30,40) i.The equivalent construct in C is theswitch statement, and in newer Fortran aSELECT CASEconstruct is the recommended syntactical alternative.BASIChad a'On GoTo'statement that achieved the same goal, but inVisual Basicthis construct is no longer supported.
In versions prior to Fortran 95, Fortran also had anassigned gotovariant 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.The Fortranassignstatement only allows a constant (existing) line number to be assigned to the integer variable. However, some compilers allowed accidentally treating this variable as an integer thereafter, for example increment it, resulting in unspecified behavior atgototime. The following code demonstrates the behavior of thegoto iwhen lineiis unspecified:
Several C compilers implement two non-standard C/C++ extensions relating to gotos originally introduced bygcc.The GNU extension allows the address of a label inside the current function to be obtained as avoid*using the unary, prefixlabel value operator&&. The goto instruction is also extended to allow jumping to an arbitraryvoid*expression. This C extension is referred to as acomputed gotoin 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.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.
Some variants of BASIC also support a computed GOTO in the sense used in GNU C, i.e. in which the target can beanyline number, not just one from a list. For example, inMTSBASIC one could writeGOTO i*1000to jump to the line numbered 1000 times the value of a variablei(which might represent a selected menu option, for example).
PL/Ilabel variablesachieve the effect of computed or assignedGOTOs.
Up to the 1985 ANSICOBOLstandard had the ALTER statement which could be used to change the destination of an existing GO TO, which had to be in a paragraph by itself.The feature, which allowedpolymorphism, was frequently condemned and seldom used.
InPerl, there is a variant of thegotostatement 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 (atail call): the new function will not return to the GOTO, but instead to the place from which the original function was called.
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,JavaScript,and Python.
PL/Ihas the data typeLABEL, 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. The value of a label variable includes the address of a stack frame, and a goto out of block pops the stack.
A simpler way to get an equivalent result is using alabel constant arraythat doesn't even need an explicit declaration of aLABELtype variable:
In a DOSbatch file, Goto directs execution to a label that begins with a colon.
The target of the Goto can be a variable.
Many languages support thegotostatement, and many do not. InJava,gotois areserved word, but is unusable, although compiled.classfiles generate GOTOs and LABELs.Python does not have support for goto, although there are several joke modules that provide it.There is no goto statement inSeed7and hidden gotos like break- and continue-statements are also omitted.InPHPthere was no native support forgotountil version 5.3 (libraries were available to emulate its functionality).
C#andVisual Basic .NETboth supportgoto.However, it does not allow jumping to a label outside of the current scope, and respects object disposal and finally constructs, making it significantly less powerful and dangerous than thegotokeyword in other programming languages. It also makescaseanddefaultstatements labels, whose scope is the enclosingswitch statement;goto caseorgoto defaultis often used as an explicit replacement for implicit fallthrough, which C# disallows.
ThePL/Iprograming language has a GOTO statement that unwinds the stack for an out of block transfer and does not permit a transfer into a block from outside of it.
Other languages may have their own separate keywords for explicit fallthroughs, which can be considered a version ofgotorestricted to this specific purpose. For example, Go uses thefallthroughkeyword and doesn't allow implicit fallthrough at all,while Perl 5 usesnextfor explicit fallthrough by default, but also allows setting implicit fallthrough as default behavior for a module.
Most languages that have goto statements call it that, but in the early days of computing, other names were used. For example, inMADthe TRANSFER TO statement was used.APLuses a right pointing arrow,→for goto.
C has goto, and it is commonly used in various idioms, as discussed above.
Functional programming languages such as Scheme generally do not have goto, instead using continuations.