In
computer programming
Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, a return statement causes
execution
Capital punishment, also known as the death penalty, is the State (polity), state-sanctioned practice of deliberately killing a person as a punishment for an actual or supposed crime, usually following an authorized, rule-governed process to ...
to leave the current
subroutine
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions may ...
and resume at the point in the code immediately after the instruction which called the subroutine, known as its return address. The return address is saved by the calling routine, today usually on the
process
A process is a series or set of activities that interact to produce a result; it may occur once-only or be recurrent or periodic.
Things called a process include:
Business and management
*Business process, activities that produce a specific se ...
's
call stack
In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or ma ...
or in a
register
Register or registration may refer to:
Arts entertainment, and media Music
* Register (music), the relative "height" or range of a note, melody, part, instrument, etc.
* ''Register'', a 2017 album by Travis Miller
* Registration (organ), the ...
. Return statements in many
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
s allow a function to specify a return value to be passed back to the
code
In communications and information processing, code is a system of rules to convert information—such as a letter, word, sound, image, or gesture—into another form, sometimes shortened or secret, for communication through a communication ...
that called the function.
Overview
In
C and
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
,
return ''exp'';
(where
''exp''
is an
expression
Expression may refer to:
Linguistics
* Expression (linguistics), a word, phrase, or sentence
* Fixed expression, a form of words with a specific meaning
* Idiom, a type of fixed expression
* Metaphorical expression, a particular word, phrase, o ...
) is a
statement that tells a function to return execution of the program to the calling function, and report the value of
''exp''
. If a function has the return type
void
Void may refer to:
Science, engineering, and technology
* Void (astronomy), the spaces between galaxy filaments that contain no galaxies
* Void (composites), a pore that remains unoccupied in a composite material
* Void, synonym for vacuum, a s ...
, the return statement can be used without a value, in which case the program just breaks out of the current function and returns to the calling one.
In
Pascal
Pascal, Pascal's or PASCAL may refer to:
People and fictional characters
* Pascal (given name), including a list of people with the name
* Pascal (surname), including a list of people and fictional characters with the name
** Blaise Pascal, Fren ...
there is no return statement. (However, in newer Pascals, the
Exit(''exp'');
can be used to return a value immediately. Without parameters, it just breaks out the procedure.) A subroutine automatically returns when execution reaches its last executable statement. Values may be returned by assigning to an identifier that has the same name as the subroutine, a ''function'' in Pascal terminology. This way the function identifier is used for recursive calls and as result holder; this is syntactically similar to an explicit
output parameter
In computer programming, a parameter or a formal argument is a special kind of variable used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are the values of the arguments (often c ...
. The same syntax is used in
Fortran 66 and
Fortran 77 although a return statement was added in
FORTRAN II. In some other languages a user defined result variable is used instead of the function identifier.
Oberon
Oberon () is a king of the fairies in medieval and Renaissance literature. He is best known as a character in William Shakespeare's play ''A Midsummer Night's Dream'', in which he is King of the Fairies and spouse of Titania, Queen of the Fair ...
(
Oberon-07
Oberon is a general-purpose programming language first published in 1987 by Niklaus Wirth and the latest member of the Wirthian family of ALGOL-like languages (Euler, ALGOL W, Pascal, Modula, and Modula-2). Oberon was the result of a concentrated ...
) has a return clause instead of a return statement. The return clause is placed after the last statement of the procedure body. This enables compile-time checking of proper return and return value from the procedure.
Some
expression-oriented programming language, such as
Lisp
A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech.
Types
* A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
,
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
and
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
, allow the programmer to omit an explicit return statement, specifying instead that the last evaluated expression is the return value of the subroutine.
In other cases a Null value is returned if there is no explicit return statement: in
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
, the value
None
is returned when the return statement is omitted, while in JavaScript the value
undefined
is returned.
In
Windows PowerShell
PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-sourc ...
all evaluated expressions which are not captured (e.g., assigned to a variable,
cast
Cast may refer to:
Music
* Cast (band), an English alternative rock band
* Cast (Mexican band), a progressive Mexican rock band
* The Cast, a Scottish musical duo: Mairi Campbell and Dave Francis
* ''Cast'', a 2012 album by Trespassers William
* ...
to
void
Void may refer to:
Science, engineering, and technology
* Void (astronomy), the spaces between galaxy filaments that contain no galaxies
* Void (composites), a pore that remains unoccupied in a composite material
* Void, synonym for vacuum, a s ...
or
piped
A pipe is a tubular section or hollow cylinder, usually but not necessarily of circular cross-section, used mainly to convey substances which can flow — liquids and gases (fluids), slurries, powders and masses of small solids. It ...
to
$null) are returned from the subroutine as elements in an array, or as a single object in the case that only one object has not been captured.
In Perl, a return value or values of a subroutine can depend on the context in which it was called. The most fundamental distinction is a
scalar
Scalar may refer to:
*Scalar (mathematics), an element of a field, which is used to define a vector space, usually the field of real numbers
* Scalar (physics), a physical quantity that can be described by a single element of a number field such ...
context where the calling code expects one value, a
list
A ''list'' is any set of items in a row. List or lists may also refer to:
People
* List (surname)
Organizations
* List College, an undergraduate division of the Jewish Theological Seminary of America
* SC Germania List, German rugby union ...
context where the calling code expects a list of values and a
void
Void may refer to:
Science, engineering, and technology
* Void (astronomy), the spaces between galaxy filaments that contain no galaxies
* Void (composites), a pore that remains unoccupied in a composite material
* Void, synonym for vacuum, a s ...
context where the calling code doesn't expect any return value at all. A subroutine can check the context using the
wantarray
function. A special syntax of return without arguments is used to return an undefined value in scalar context and an empty list in list context. The scalar context can be further divided into
Boolean, number,
string
String or strings may refer to:
*String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects
Arts, entertainment, and media Films
* ''Strings'' (1991 film), a Canadian anim ...
, and various
reference
Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''name'' ...
types contexts. Also, a context-sensitive
object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
can be returned using a contextual return sequence, with
lazy evaluation
In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (sharing).
The b ...
of scalar values.
Many
operating system
An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs.
Time-sharing operating systems schedule tasks for efficient use of the system and may also in ...
s let a program return a result (separate from normal
output
Output may refer to:
* The information produced by a computer, see Input/output
* An output state of a system, see state (computer science)
* Output (economics), the amount of goods and services produced
** Gross output in economics, the value of ...
) when its process terminates; these values are referred to as
return code
In computer programming, a return code or an error code is a numeric or alphanumeric code that is used to determine the nature of an error and why it occurred. They are also commonly found in consumer electronics and devices when they attempt to ...
s, or more specifically
exit status
The exit status of a process in computer programming is a small number passed from a child process (or callee) to a parent process (or caller) when it has finished executing a specific procedure or delegated task. In DOS, this may be referred t ...
es. The amount of information that can be passed this way is quite limited, in practice often restricted to signalling success or fail. From within the program this return is typically achieved by calling
Exit (system call)
On many computer operating systems, a computer process terminates its execution by making an exit system call. More generally, an exit in a multithreading environment means that a thread of execution has stopped running. For resource managemen ...
(common even in C, where the alternative mechanism of returning from the
main function
In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.
To start a program's execution, the loader or operating system passes contro ...
is available).
Syntax
Return statements come in many shapes. The following syntaxes are most common:
In some
assembly language
In computer programming, assembly language (or assembler language, or symbolic machine code), often referred to simply as Assembly and commonly abbreviated as ASM or asm, is any low-level programming language with a very strong correspondence be ...
s, for example that for the
MOS Technology 6502
The MOS Technology 6502 (typically pronounced "sixty-five-oh-two" or "six-five-oh-two") William Mensch and the moderator both pronounce the 6502 microprocessor as ''"sixty-five-oh-two"''. is an 8-bit microprocessor that was designed by a small t ...
, the mnemonic "RTS" (ReTurn from Subroutine) is used.
Multiple return statements
Languages with an explicit return statement create the possibility of multiple return statements in the same function.
Whether or not that is a good thing is controversial.
Strong adherents of
structured programming
Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of selection ( if/then/else) and repetition ( ...
make sure each function has a single entry and a single exit (SESE).
It has thus been argued that one should eschew the use of the explicit return statement except at the textual end of a subroutine, considering that, when it is used to "return early", it may suffer from the same sort of problems that arise for the
GOTO
GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function ca ...
statement. Conversely, it can be argued that using the return statement is worthwhile when the alternative is more convoluted code, such as deeper nesting, harming readability.
In his 2004 textbook,
David Watt writes that "single-entry multi-exit control flows are often desirable". Using Tennent's framework notion of
sequencer
Sequencer may refer to:
Technology
* Drum sequencer (controller), an electromechanical system for controlling a sequence of events automatically
* DNA sequencer, a machine used to automatically produce a sequence readout from a biological DNA sam ...
, Watt uniformly describes the control flow constructs found in contemporary programming languages and attempts to explain why certain types of sequencers are preferable to others in the context of multi-exit control flows. Watt writes that unrestricted gotos (jump sequencers) are bad because the destination of the jump is not self-explanatory to the reader of a program until the reader finds and examines the actual label or address that is the target of the jump. In contrast, Watt argues that the conceptual intent of a return sequencer is clear from its own context, without having to examine its destination. Furthermore, Watt writes that a class of sequencers known as ''escape sequencers'', defined as "sequencer that terminates execution of a textually enclosing command or procedure", encompasses both
break
Break or Breaks or The Break may refer to:
Time off from duties
* Recess (break), time in which a group of people is temporarily dismissed from its duties
* Break (work), time off during a shift/recess
** Coffee break, a short mid-morning rest ...
s from loops (including multi-level breaks) and return statements. Watt also notes that while jump sequencers (gotos) have been somewhat restricted in languages like C, where the target must be an inside the local block or an encompassing outer block, that restriction alone is not sufficient to make the intent of gotos in C self-describing and so they can still produce "
spaghetti code
Spaghetti code is a pejorative phrase for unstructured and difficult-to- maintain source code. Spaghetti code can be caused by several factors, such as volatile project requirements, lack of programming style rules, and software engineers with insu ...
". Watt also examines how exception sequencers differ from escape and jump sequencers; for details on this see the article on
structured programming
Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of selection ( if/then/else) and repetition ( ...
.
According to empirical studies cited by
Eric S. Roberts
Eric S. Roberts is an American computer scientist noted for his contributions to computer science education through textbook authorship and his leadership in computing curriculum development. He is a co-chair of the ACM Education Council, forme ...
, student programmers had difficulty formulating correct solutions for several simple problems in a language like
Pascal
Pascal, Pascal's or PASCAL may refer to:
People and fictional characters
* Pascal (given name), including a list of people with the name
* Pascal (surname), including a list of people and fictional characters with the name
** Blaise Pascal, Fren ...
, which doesn't allow multiple exit points. For the problem of writing a function to linearly searching an element in an array, a 1980 study by Henry Shapiro (cited by Roberts) found that using only the Pascal-provided control structures, the correct solution was given by only 20% of the subjects, while no subject wrote incorrect code for this problem if allowed to write a return from the middle of a loop.
[Roberts, E. ]995
Year 995 (Roman numerals, CMXCV) was a common year starting on Tuesday (link will display the full calendar) of the Julian calendar.
Events
By place
Japan
* 17 May - Fujiwara no Michitaka (imperial regent) dies.
* 3 June: Fujiwara no ...
“Loop Exits and Structured Programming: Reopening the Debate,” ACM SIGCSE Bulletin, (27)1: 268–272.
Others, including
Kent Beck
Kent Beck (born 1961) is an American software engineer and the creator of extreme programming, a software development methodology that eschews rigid formal specification for a collaborative and iterative design process. Beck was one of the 17 ori ...
and
Martin Fowler argue that one or more
guard clauses -- conditional "early exit" return statements near the beginning of a function -- often make a function easier to read than the alternative.
The most common problem in early exit is that cleanup or final statements are not executed – for example, allocated memory is not unallocated, or open files are not closed, causing leaks. These must be done at each return site, which is brittle and can easily result in bugs. For instance, in later development, a return statement could be overlooked by a developer, and an action which should be performed at the end of a subroutine (e.g., a
trace
Trace may refer to:
Arts and entertainment Music
* Trace (Son Volt album), ''Trace'' (Son Volt album), 1995
* Trace (Died Pretty album), ''Trace'' (Died Pretty album), 1993
* Trace (band), a Dutch progressive rock band
* The Trace (album), ''The ...
statement) might not be performed in all cases. Languages without a return statement, such as standard
Pascal
Pascal, Pascal's or PASCAL may refer to:
People and fictional characters
* Pascal (given name), including a list of people with the name
* Pascal (surname), including a list of people and fictional characters with the name
** Blaise Pascal, Fren ...
don't have this problem. Some languages, such as C++ and Python, employ concepts which allow actions to be performed automatically upon return (or exception throw) which mitigates some of these issues – these are often known as "try/finally" or similar. Functionality like these "finally" clauses can be implemented by a goto to the single return point of the subroutine. An alternative solution is to use the normal stack unwinding (variable deallocation) at function exit to unallocate resources, such as via destructors on local variables, or similar mechanisms such as Python's "with" statement.
Some early implementations of languages such as the original Pascal and C restricted the types that can be returned by a function (e.g., not supporting
record or
struct
In computer science, a record (also called a structure, struct, or compound data) is a basic data structure. Records in a database or spreadsheet are usually called "rows".
A record is a collection of '' fields'', possibly of different data typ ...
types) to simplify their
compiler
In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
s.
In
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
—and similar languages modeled after it, like
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
—it is possible to execute code even after return statement, because the ''finally'' block of a
try-catch structure is always executed. So if the ''return'' statement is placed somewhere within ''try'' or ''catch'' blocks the code within ''finally'' (if added) will be executed. It is even possible to alter the return value of a non primitive type (a property of an already returned object) because the exit occurs afterwards as well.
The finally Block,The Java Tutorials
/ref>
Yield statements
Cousin to return statements are yield statements: where a return causes a ''sub''routine to ''terminate,'' a yield causes a ''co''routine to ''suspend.'' The coroutine will later continue from where it suspended if it is called again. Coroutines are significantly more involved to implement than subroutines, and thus yield statements are less common than return statements, but they are found in a number of languages.
Call/return sequences
A number of possible call/return sequences are possible depending on the hardware instruction set, including the following:
# The CALL
instruction pushes address of the next instruction on the stack and branches to the specified address. The RETURN
instruction pops the return address from the stack into the instruction pointer and execution resumes at that address. (Examples: x86
x86 (also known as 80x86 or the 8086 family) is a family of complex instruction set computer (CISC) instruction set architectures initially developed by Intel based on the Intel 8086 microprocessor and its 8088 variant. The 8086 was introd ...
, PDP-11
The PDP-11 is a series of 16-bit minicomputers sold by Digital Equipment Corporation (DEC) from 1970 into the 1990s, one of a set of products in the Programmed Data Processor (PDP) series. In total, around 600,000 PDP-11s of all models were sold, ...
)
# The CALL
instruction places address of the next instruction in a register and branches to the specified address. The RETURN
instruction sequence places the return address from the register into the instruction pointer and execution resumes at that address. (Examples: IBM System/360
The IBM System/360 (S/360) is a family of mainframe computer systems that was announced by IBM on April 7, 1964, and delivered between 1965 and 1978. It was the first family of computers designed to cover both commercial and scientific applica ...
and successors through z/Architecture
z/Architecture, initially and briefly called ESA Modal Extensions (ESAME), is IBM's 64-bit complex instruction set computer (CISC) instruction set architecture, implemented by its mainframe computers. IBM introduced its first z/Architecture-b ...
, most RISC
In computer engineering, a reduced instruction set computer (RISC) is a computer designed to simplify the individual instructions given to the computer to accomplish tasks. Compared to the instructions given to a complex instruction set comput ...
architectures)
# The CALL
instruction places address of the next (or current) instruction in the storage location at the call address and branches to the specified address+1. The RETURN
instruction sequence branches to the return address by an indirect jump to the first instruction of the subroutine. (Examples: IBM 1130
The IBM 1130 Computing System, introduced in 1965, was IBM's least expensive computer at that time. A binary 16-bit machine, it was marketed to price-sensitive, computing-intensive technical markets, like education and engineering, succeeding th ...
, SDS 9XX, PDP-8
The PDP-8 is a 12-bit computing, 12-bit minicomputer that was produced by Digital Equipment Corporation, Digital Equipment Corporation (DEC). It was the first commercially successful minicomputer, with over 50,000 units being sold over the model's ...
)
See also
*Return type
In computer programming, the return type (or result type) defines and constrains the data type of the value returned from a subroutine or method. In many programming languages (especially statically-typed programming languages such as C, C++, ...
*Exit status
The exit status of a process in computer programming is a small number passed from a child process (or callee) to a parent process (or caller) when it has finished executing a specific procedure or delegated task. In DOS, this may be referred t ...
References
{{DEFAULTSORT:Return Statement
BASIC commands
Subroutines