HOME

TheInfoList



OR:

Goto is a
statement Statement or statements may refer to: Common uses *Statement (computer science), the smallest standalone element of an imperative programming language *Statement (logic and semantics), declarative sentence that is either true or false *Statement, ...
found in many computer
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s. It performs a one-way transfer of control to another line of code; in contrast a
function call In computer programming, a function (also procedure, method, subroutine, routine, or subprogram) is a callable unit of software logic that has a well-defined interface and behavior and can be invoked multiple times. Callable units provide a p ...
normally returns control. The jumped-to locations are usually identified using
labels A label (as distinct from signage) is a piece of paper, plastic film, cloth, metal, or other material affixed to a container or product. Labels are most often affixed to packaging and containers using an adhesive, or sewing when affixed to ...
, though some languages use
line number In computing, a line number is a method used to specify a particular sequence of characters in a text file. The most common method of assigning numbers to lines is to assign every line a unique number, starting at 1 for the first line, and increm ...
s. At the
machine code In computer programming, machine code is computer code consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). For conventional binary computers, machine code is the binaryOn nonb ...
level, a goto is a form of branch or jump statement, in some cases combined with a stack adjustment. Many languages support the goto statement, and many do not (see § language support). The
structured program theorem The structured program theorem, also called the Böhm–Jacopini theorem, is a result in programming language theory. It states that a class of control-flow graphs (historically called flowcharts in this context) can compute any computable functi ...
proved that the goto statement is not necessary to write programs that can be expressed as
flow chart A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be defined as a diagrammatic representation of an algorithm, a step-by-step approach to solving a task. The flowchart shows the steps as boxes of va ...
s; 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 A Turing machine is a mathematical model of computation describing an abstract machine that manipulates symbols on a strip of tape according to a table of rules. Despite the model's simplicity, it is capable of implementing any computer algori ...
, with the caveat that code duplication and additional variables may need to be introduced. The use of goto was formerly common, but since the advent of
structured programming Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making specific disciplined use of the structured control flow constructs of selection ( if/then/else) and repet ...
in the 1960s and 1970s, its use has declined significantly. It remains in use in certain common usage patterns, but
alternatives Founded in 1994, Alternatives, Action and Communication Network for International Development, is a non-governmental, international solidarity movement, international solidarity organization based in Montreal, Quebec, Canada. Alternatives works ...
are 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 primary
criticism Criticism is the construction of a judgement about the negative or positive qualities of someone or something. Criticism can range from impromptu comments to a written detailed response. , ''the act of giving your opinion or judgment about the ...
is 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.


Usage

goto ''label'' The goto statement is often combined with the
if statement In computer science, conditionals (that is, conditional statements, conditional expressions and conditional constructs) are programming language constructs that perform different computations or actions or return different values depending on t ...
to cause a conditional transfer of control. IF ''condition'' THEN goto ''label'' Programming languages impose different restrictions with respect to the destination of a goto statement. For example, the
C programming language C (''pronounced'' '' – like the letter c'') is a general-purpose programming language. It was created in the 1970s by Dennis Ritchie and remains very widely used and influential. By design, C's features cleanly reflect the capabilities of ...
does not permit a jump to a label contained within another function, however jumps within a single call chain are possible using the setjmp/longjmp functions.


Criticism

At the pre-ALGOL meeting held in 1959, Heinz Zemanek explicitly cast doubt on the necessity of GOTO statements; at the time no one paid attention to his remark, including
Edsger W. Dijkstra Edsger Wybe Dijkstra ( ; ; 11 May 1930 – 6 August 2002) was a Dutch computer scientist, programmer, software engineer, mathematician, and science essayist. Born in Rotterdam in the Netherlands, Dijkstra studied mathematics and physics and the ...
, who later became the iconic opponent of GOTO. The 1970s and 1980s saw a decline in the use of GOTO statements in favor of the
structured programming Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making specific disciplined use of the structured control flow constructs of selection ( if/then/else) and repet ...
paradigm In science and philosophy, a paradigm ( ) is a distinct set of concepts or thought patterns, including theories, research methods, postulates, and standards for what constitute legitimate contributions to a field. The word ''paradigm'' is Ancient ...
, with GOTO criticized as leading to unmaintainable spaghetti code. Some
programming style Programming style, also known as coding style, are the conventions and patterns used in writing source code, resulting in a consistent and readable codebase. These conventions often encompass aspects such as indentation, naming conventions, cap ...
coding standards, for example the GNU Pascal Coding Standards, recommend against the use of GOTO statements. 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. 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" letter 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''. An alternative viewpoint is presented in
Donald Knuth Donald Ervin Knuth ( ; born January 10, 1938) is an American computer scientist and mathematician. He is a professor emeritus at Stanford University. He is the 1974 recipient of the ACM Turing Award, informally considered the Nobel Prize of comp ...
'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 In computer programming, a language construct is "a syntactically allowable part of a program that may be formed from one or more lexical tokens in accordance with the rules of the programming language", as defined by in the ISO/IEC 2382 stan ...
to use. In ''
The C Programming Language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the C programming langu ...
'',
Brian Kernighan Brian Wilson Kernighan (; born January 30, 1942) is a Canadian computer scientist. He worked at Bell Labs and contributed to the development of Unix alongside Unix creators Ken Thompson and Dennis Ritchie. Kernighan's name became widely known ...
and
Dennis Ritchie Dennis MacAlistair Ritchie (September 9, 1941 – October 12, 2011) was an American computer scientist. He created the C programming language and the Unix operating system and B language with long-time colleague Ken Thompson. Ritchie and Thomp ...
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. 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, including
Linux Linux ( ) is a family of open source Unix-like operating systems based on the Linux kernel, an kernel (operating system), operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically package manager, pac ...
kernel designer and coder
Linus Torvalds Linus Benedict Torvalds ( , ; born 28 December 1969) is a Finnish software engineer who is the creator and lead developer of the Linux kernel. He also created the distributed version control system Git. He was honored, along with Shinya Yam ...
or software engineer and book author
Steve McConnell Steven C. McConnell is an author of software engineering textbooks such as '' Code Complete'', ''Rapid Development'', and ''Software Estimation''. He is cited as an expert in software engineering and project management. Career McConnell gradua ...
, 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 professor John 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 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. For instance,
Bertrand Meyer Bertrand Meyer (; ; born 21 November 1950) is a French academic, author, and consultant in the field of computer languages. He created the Eiffel programming language and the concept of design by contract. Education and academic career Meyer ...
wrote in his 2009 textbook that instructions like break and continue "are just the old goto in 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 their break keyword, some textbooks advise the programmer to use goto in such circumstances. The
MISRA C MISRA C is a set of software development guidelines for the C (programming language), C programming language developed by Motor Industry Software Reliability Association, The MISRA Consortium. Its aims are to facilitate code safety, Computer secur ...
2004 standard bans goto, continue, as well as multiple return and break statements. 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. 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 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 as
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
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 visually emphasizes label definitions using angle brackets. Entry 17.10 in comp.lang.c FAQ list addresses the issue of GOTO use directly, stating


Common usage patterns

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: * To make the code more readable and easier to follow * To make smaller programs, and get rid of code duplication * Implement a
finite-state machine A finite-state machine (FSM) or finite-state automaton (FSA, plural: ''automata''), finite automaton, or simply a state machine, is a mathematical model of computation. It is an abstract machine that can be in exactly one of a finite number o ...
, using a
state transition table In automata theory and sequential logic, a state-transition table is a table showing what state (or states in the case of a nondeterministic finite automaton) a finite-state machine will move to, based on the current state and other inputs. It i ...
and goto to switch between states (in absence of tail call elimination), particularly in automatically generated C code. For example, goto in the canonical LR parser. * Implementing multi-level break and continue if not directly supported in the language; this is a common idiom in C. Although Java reserves the goto keyword, it doesn't actually implement it. Instead, Java implements labelled break and labelled continue statements. According to the Java documentation, the use of gotos for multi-level breaks was the most common (90%) use of gotos in C. Java was not the first language to take this approach—forbidding goto, but providing multi-level breaks— the
BLISS BLISS is a system programming language developed at Carnegie Mellon University (CMU) by W. A. Wulf, D. B. Russell, and A. N. Habermann around 1970. It was perhaps the best known system language until C debuted a few years later. Since then, C ...
programming language (more precisely the BLISS-11 version thereof) preceded it in this respect. * 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 NetBSD is a free and open-source Unix-like operating system based on the Berkeley Software Distribution (BSD). It was the first open-source BSD descendant officially released after 386BSD was fork (software development), forked. It continues to ...
code. * Error handling (in absence of exceptions), particularly cleanup code such as resource deallocation. C++ offers an alternative to goto statement for this use case, which is :
Resource Acquisition Is Initialization Resource acquisition is initialization (RAII) is a programming idiom used in several object-oriented, statically typed programming languages to describe a particular language behavior. In RAII, holding a resource is a class invariant, and is tie ...
(RAII) through using destructors or using try and catch exceptions used in
Exception handling In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
.
setjmp setjmp.h is a header defined in the C standard library to provide "non-local jumps": control flow that deviates from the usual subroutine call and return sequence. The complementary functions setjmp and longjmp provide this functionality. A t ...
and longjmp are another alternative, and have the advantage of being able to unwind part of the
call stack In computer science, a call stack is a Stack (abstract data type), stack data structure that stores information about the active subroutines and block (programming), inline blocks of a computer program. This type of stack is also known as an exe ...
. * Popping the stack in, e.g., Algol, PL/I. * Specialized scripting languages that operate in a linear manner, such as a dialogue system for video games. 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 is
Objective-C Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was ...
, where a goto is a much faster alternative. Another use of goto statements is to modify poorly factored
legacy code Legacy or Legacies may refer to: Arts and entertainment Comics * " Batman: Legacy", a 1996 Batman storyline * '' DC Universe: Legacies'', a comic book series from DC Comics * ''Legacy'', a 1999 quarterly series from Antarctic Press * ''Legacy ...
, where avoiding a goto would require extensive
refactoring In computer programming and software design, code refactoring is the process of restructuring existing source code—changing the '' factoring''—without changing its external behavior. Refactoring is intended to improve the design, structure, ...
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 In computer programming, a code smell is any characteristic in the source code of a program that possibly indicates a deeper problem. Determining what is and is not a code smell is subjective, and varies by language, developer, and development met ...
, but finds occasional use.


Alternatives


Structured programming

The modern notion of
subroutine In computer programming, a function (also procedure, method, subroutine, routine, or subprogram) is a callable unit of software logic that has a well-defined interface and behavior and can be invoked multiple times. Callable units provide a ...
was invented by David Wheeler when programming the
EDSAC The Electronic Delay Storage Automatic Calculator (EDSAC) was an early British computer. Inspired by John von Neumann's seminal ''First Draft of a Report on the EDVAC'', the machine was constructed by Maurice Wilkes and his team at the Universit ...
. 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 a Wheeler 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 only goto, since the target code, being drawn from the library, would not know where to jump back to. Later, high-level languages such as Pascal were designed around support for
structured programming Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making specific disciplined use of the structured control flow constructs of selection ( if/then/else) and repet ...
, which generalized from
subroutine In computer programming, a function (also procedure, method, subroutine, routine, or subprogram) is a callable unit of software logic that has a well-defined interface and behavior and can be invoked multiple times. Callable units provide a ...
s (also known as procedures or functions) towards further control structures such as: * Loops using while, repeat until or do, and for statements * switch a.k.a. case statements, a form of
multiway branch Multiway branch is the change to a program's control flow based upon a value matching a selected criteria. It is a form of conditional statement. A multiway branch is often the most efficient method of passing control to one of a set of program ...
ing These new language mechanisms replaced 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). Under certain conditions it is possible to eliminate local goto statements of legacy programs by replacing them with multilevel loop exit statements.


Exceptions

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 In mathematics, a combinatorial explosion is the rapid growth of the complexity of a problem due to the way its combinatorics depends on input, constraints and bounds. Combinatorial explosion is sometimes used to justify the intractability of cert ...
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 In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
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.


Tail calls

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. Since such "tail calls" are very common in
Lisp Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation. Originally specified in the late 1950s, ...
, 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 In computer programming, machine code is computer code consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). For conventional binary computers, machine code is the binaryOn nonb ...
JUMP 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. In Scheme, a Lisp dialect developed by Steele with Gerald 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 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 machine A finite-state machine (FSM) or finite-state automaton (FSA, plural: ''automata''), finite automaton, or simply a state machine, is a mathematical model of computation. It is an abstract machine that can be in exactly one of a finite number o ...
s, which otherwise is generally accomplished with goto statements.


Coroutines

Coroutine Coroutines are computer program components that allow execution to be suspended and resumed, generalizing subroutines for cooperative multitasking. Coroutines are well-suited for implementing familiar program components such as cooperative task ...
s 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 variable In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
s), 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.


Continuations

A
continuation In computer science, a continuation is an abstract representation of the control state of a computer program. A continuation implements ( reifies) the program control state, i.e. the continuation is a data structure that represents the computat ...
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 computer science, a call stack is a Stack (abstract data type), stack data structure that stores information about the active subroutines and block (programming), inline blocks of a computer program. This type of stack is also known as an exe ...
in addition to a jump. The longjmp function of the
C programming language C (''pronounced'' '' – like the letter c'') is a general-purpose programming language. It was created in the 1970s by Dennis Ritchie and remains very widely used and influential. By design, C's features cleanly reflect the capabilities of ...
is an example of an escape continuation that may be used to escape the current context to a surrounding one. The
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
GO operator also has this stack unwinding property, despite the construct being
lexically scoped In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
, 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.


Message passing

In non-procedural paradigms, goto is less relevant or completely absent. One of the main alternatives is
message passing In computer science, message passing is a technique for invoking behavior (i.e., running a program) on a computer. The invoking program sends a message to a process (which may be an actor or object) and relies on that process and its supporting ...
, which is of particular importance in
concurrent computing Concurrent computing is a form of computing in which several computations are executed '' concurrently''—during overlapping time periods—instead of ''sequentially—''with one completing before the next starts. This is a property of a syst ...
,
interprocess communication In computer science, interprocess communication (IPC) is the sharing of data between running processes in a computer system. Mechanisms for IPC may be provided by an operating system. Applications which use IPC are often categorized as clients ...
, and
object oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impleme ...
. 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 via preemption. The influential languages
Simula Simula is the name of two simulation programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard. Syntactically, it is an approximate superset of AL ...
and
Smalltalk Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
were among the first to introduce the concepts of messages and objects. By encapsulating state data,
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
reduced software complexity to interactions (messages) between objects.


Variations

There are a number of different language constructs under the class of ''goto'' statements.


and

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 In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map. Switch statements function ...
, and in newer Fortran a SELECT CASE construct is the recommended syntactical alternative.
BASIC Basic or BASIC may refer to: Science and technology * BASIC, a computer programming language * Basic (chemistry), having the properties of a base * Basic access authentication, in HTTP Entertainment * Basic (film), ''Basic'' (film), a 2003 film ...
had a 'On GoTo' statement that achieved the same goal, but in
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to: * Visual Basic (.NET), the current version of Visual Basic launched in 2002 which runs on .NET * Visual Basic (classic), the original Visual Basic suppo ...
this construct is no longer supported. In versions prior to Fortran 95, 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. The Fortran assign statement 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 at goto time. The following code demonstrates the behavior of the goto i when line i is unspecified: assign 200 to i i = i+1 goto i ! unspecified behavior 200 write(*,*) "this is valid line number" Several C compilers implement two non-standard C/C++ extensions relating to gotos originally introduced by gcc. 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. 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 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).
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language initially developed by IBM. It is designed for scientific, engineering, business and system programming. It has b ...
''label variables'' achieve the effect of computed or assigned GOTOs.


ALTER

Up to the 1985 ANSI
COBOL COBOL (; an acronym for "common business-oriented language") is a compiled English-like computer programming language designed for business use. It is an imperative, procedural, and, since 2002, object-oriented language. COBOL is primarily ...
standard 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 allowed polymorphism, was frequently condemned and seldom used.


Perl GOTO

In
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
, 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 In computer science, a tail call is a subroutine call performed as the final action of a procedure. If the target of a tail is the same subroutine, the subroutine is said to be tail recursive, which is a special case of direct recursion. Tail recur ...
): the new function will not return to the GOTO, but instead to the place from which the original function was called.


Emulated GOTO

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/I label variables

PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language initially developed by IBM. It is designed for scientific, engineering, business and system programming. It has b ...
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. The value of a label variable includes the address of a stack frame, and a goto out of block pops the stack.
 /* This implements the equivalent of */
 /* the assigned goto                 */
   declare where label;
   where = somewhere;
   goto where;
   ...
 somewhere: /* statement */ ;
   ...
 /* This implements the equivalent of */
 /* the computed goto                 */
   declare where (5) label;
   declare inx fixed;
   where(1) = abc;
   where(2) = xyz;
   ...
   goto where(inx);
   ...
 abc: /* statement */ ;
   ...
 xyz: /* statement */ ;
   ...
A simpler way to get an equivalent result is using a ''label constant array'' that doesn't even need an explicit declaration of a LABEL type variable:
 /* This implements the equivalent of */
 /* the computed goto                 */
   declare inx fixed;
   ...
   goto where(inx);
   ...
 where(1): /* statement */ ;
   ...
 where(2): /* statement */ ;
   ...


MS/DOS GOTO

In a DOS
batch file A batch file is a Scripting language, script file in DOS, OS/2 and Microsoft Windows. It consists of a series of Command (computing), commands to be executed by the command-line interpreter, stored in a plain text file. A batch file may contain a ...
, Goto directs execution to a label that begins with a colon. The target of the Goto can be a variable. @echo off SET D8str=%date% SET D8dow=%D8str:~0,3% FOR %%D in (Mon Wed Fri) do if "%%D"

"%D8dow%" goto SHOP%%D echo Today, %D8dow%, is not a shopping day. goto end :SHOPMon echo buy pizza for lunch - Monday is Pizza day. goto end :SHOPWed echo buy Calzone to take home - today is Wednesday. goto end :SHOPFri echo buy Seltzer in case somebody wants a zero calorie drink. :end


Language support

Many languages support the goto statement, and many do not. In
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
, goto is a
reserved word In a programming language, a reserved word (sometimes known as a reserved identifier) is a word that cannot be used by a programmer as an identifier, such as the name of a variable, function, or label – it is "reserved from use". In brief, an '' ...
, but is unusable, although compiled .class files 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 in
Seed7 Seed7 is an extensible general-purpose programming language designed by Thomas Mertes. It is syntactically similar to Pascal and Ada. Along with many other features, it provides an extension mechanism. Daniel Zingaro"Modern Extensible Languag ...
and hidden gotos like break- and continue-statements are also omitted. In
PHP PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. ...
there was no native support for goto until version 5.3 (libraries were available to emulate its functionality). C# and Visual Basic .NET both support goto. 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 the goto keyword in other programming languages. It also makes ''case'' and ''default'' statements labels, whose scope is the enclosing
switch statement In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map. Switch statements function ...
; ''goto case'' or ''goto default'' is often used as an explicit replacement for implicit fallthrough, which C# disallows. The
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language initially developed by IBM. It is designed for scientific, engineering, business and system programming. It has b ...
programing 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 of goto restricted to this specific purpose. For example, Go uses the fallthrough keyword and doesn't allow implicit fallthrough at all, while Perl 5 uses next for 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, in MAD the TRANSFER TO statement was used. APL uses 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.


See also

* COMEFROM *
Control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
*
GOSUB Basic or BASIC may refer to: Science and technology * BASIC, a computer programming language * Basic (chemistry), having the properties of a base * Basic access authentication, in HTTP Entertainment * Basic (film), ''Basic'' (film), a 2003 film ...
*
Switch statement In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map. Switch statements function ...
– a
multiway branch Multiway branch is the change to a program's control flow based upon a value matching a selected criteria. It is a form of conditional statement. A multiway branch is often the most efficient method of passing control to one of a set of program ...
(or conditional goto) *
Non-structured programming Non-structured programming is the historically earliest programming paradigm capable of creating Turing-complete algorithms. It is often contrasted with the structured programming paradigm, in particular with the use of unstructured control flo ...


Notes


References

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * {{refend BASIC commands Control flow Edsger W. Dijkstra