Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Return statement
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Statement which ends execution of a function and resumes in the main code}} {{More citations needed|date=February 2011}} In [[computer programming]], a '''return statement''' causes [[Execution (computing)|execution]] to leave the current [[subroutine]] 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 (computing)|process]]'s [[call stack]] or in a [[Register (computing)|register]]. Return statements in many [[programming language]]s allow a function to specify a '''return value''' to be passed back to the [[Source code|code]] that called the function. == Overview == In [[C (programming language)|C]] and [[C++]], <code>return ''exp'';</code> (where <code>''exp''</code> is an [[Expression (programming)|expression]]) is a [[Statement (programming)|statement]] that tells a function to return execution of the program to the calling function, and report the value of <code>''exp''</code>. If a function has the return type [[Void type|void]], 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.<ref name=msc/><ref name=mscpp/> Similar syntax is used in other languages including [[Modula-2]]<ref>{{cite book|title=Modula-2 for Pascal Programmers|first=R.|last=Gleaves|publisher=Springer|year=2012|isbn=9781461385318|page=71|url=https://books.google.com/books?id=pvzSBwAAQBAJ&pg=PA71}}</ref> and [[Python (programming language)|Python]].<ref name=python>{{cite book|title=Python in a Nutshell: A Desktop Quick Reference|first=Alex|last=Martelli|edition=2nd|publisher=O'Reilly Media|year=2006|isbn=9781449379100|page=73|url=https://books.google.com/books?id=JnR9hQA3SncC&pg=PA73}}</ref> In [[Pascal (programming language)|Pascal]] there is no return statement. Functions or procedures automatically return when reaching their last statement. The return value from a function is provided within the function by making an assignment to an identifier with the same name as the function.<ref name=scott>{{cite book|title=Programming Language Pragmatics|first=Michael L.|last=Scott|publisher=Morgan Kaufmann|year=2006|isbn=9780126339512|page=432|url=https://books.google.com/books?id=TLbvODF1uIEC&pg=PA432}}</ref> However, some versions of Pascal provide a special function <code>Exit(''exp'');</code> that can be used to return a value immediately from a function, or, without parameters, to return immediately from a procedure.<ref>{{cite book|title=Scientific Pascal|first=Harley|last=Flanders|publisher=Springer|year=2012|isbn=9781461224280|page=35|url=https://books.google.com/books?id=D7gPBwAAQBAJ&pg=PA35}}</ref> Like Pascal, [[FORTRAN II]], [[Fortran 66]], [[Fortran 77]], and later versions of [[Fortran]] specify return values by an assignment to the function name, but also have a return statement; that statement does not specify a return value and, for a function, causes the value assigned to the function name to be returned.<ref name=scott/><ref>{{Cite book | last = ANSI x3.9-1966 | title = USA Standard FORTRAN | publisher = American National Standards Institute | url = http://www.fh-jena.de/~kleine/history/languages/ansi-x3dot9-1966-Fortran66.pdf | access-date = May 5, 2010 | page = 14 | archive-date = May 15, 2011 | archive-url = https://web.archive.org/web/20110515143149/http://www.fh-jena.de/~kleine/history/languages/ansi-x3dot9-1966-Fortran66.pdf | url-status = dead}}</ref><ref>{{Cite book | last = ANSI x3.9-1978 | title = American National Standard – Programming Language FORTRAN | publisher = American National Standards Institute | url = http://www.fortran.com/fortran/F77_std/rjcnf.html | at = 15.8 RETURN Statement | access-date = December 11, 2007 | archive-url = https://web.archive.org/web/20131029134137/http://www.fortran.com/fortran/F77_std/rjcnf.html | archive-date = October 29, 2013 | url-status = dead }}</ref> In some other languages a user defined [[output parameter]] is used instead of the function identifier.<ref>{{cite journal | last = Sakkinen | first = Markku | date = March 1989 | doi = 10.1145/66083.66087 | issue = 3 | journal = ACM SIGPLAN Notices | pages = 55–56 | publisher = Association for Computing Machinery | title = How to best return the value of a function | volume = 24| doi-access = free }}</ref> [[Oberon (programming language)|Oberon]] ([[Oberon-07]]) has a return clause instead of a return statement. The return clause is placed after the last statement of the procedure body.<ref>{{cite report|title=The Programming Language Oberon|first=Niklaus|last=Wirth|author-link=Niklaus Wirth|date=May 3, 2016|url=https://people.inf.ethz.ch/wirth/Oberon/Oberon07.Report.pdf|contribution=10. Procedure declarations|page=11}}</ref> Some [[expression-oriented programming language]], such as [[Lisp (programming language)|Lisp]], [[Perl]] and [[Ruby (programming language)|Ruby]], 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 (programming language)|Python]], the value <code>None</code> is returned when the return statement is omitted,<ref name=python/> while in JavaScript the value <code>undefined</code> is returned. In [[Windows PowerShell]] all evaluated expressions which are not captured (e.g., assigned to a variable, [[Type conversion|cast]] to [[Void type|void]] or [[Pipeline (Unix)|piped]] to [[/dev/null|$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 (computing)|scalar]] context where the calling code expects one value, a [[List (computing)|list]] context where the calling code expects a list of values and a [[Void type|void]] context where the calling code doesn't expect any return value at all. A subroutine can check the context using the <code>wantarray</code> 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 data type|Boolean]], number, [[String (computer science)|string]], and various [[Reference (computer science)|reference]] types contexts. Also, a context-sensitive [[Object (computer science)|object]] can be returned using a contextual return sequence, with [[lazy evaluation]] of scalar values. Many [[operating system]]s let a program return a result (separate from normal [[Standard streams|output]]) when its process terminates; these values are referred to [[exit status]]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)]] (common even in C, where the alternative mechanism of returning from the [[main function]] is available). ==Syntax== Return statements come in many shapes. The following syntaxes are most common: {| class="wikitable" |- ! Language ! Return statement ! If value omitted, return |- | [[Ada (programming language)|Ada]], [[Bourne shell]],{{efn|in the Bourne shell, only integers in the range 0-255 may be returned<ref>{{cite web |url=https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#return |title=return - return from a function or dot script |work=Single UNIX Specification}}</ref>}} [[C (programming language)|C]], [[C++]], [[Java (programming language)|Java]], [[PHP]], [[C Sharp (programming language)|C#]], [[JavaScript]], [[D (programming language)|D]] | <syntaxhighlight lang="c">return value;</syntaxhighlight> | In the Bourne shell, exit value of the last command executed in the function In C<ref name=msc>{{cite web |url=https://learn.microsoft.com/en-us/cpp/c-language/return-statement-c |title=return Statement (C) |website=[[Microsoft Docs]]|date=25 January 2023 }}</ref> and C++,<ref name=mscpp>{{cite web |url=https://learn.microsoft.com/en-us/cpp/cpp/return-statement-cpp |title=return Statement (C++) |website=[[Microsoft Docs]] |date=3 August 2021 }}</ref> [[undefined behavior]] if function is value-returning In PHP,<ref>{{cite web|title=PHP: return - Manual |url=http://www.php.net/manual/en/function.return.php |work=PHP Manual |publisher=The PHP Group |access-date=26 March 2013 }}</ref> returns <code>NULL</code> In Javascript,<ref>{{cite web |title=Return - Javascript |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return |work=MDN Javascript Reference |publisher=Mozilla Developer Network |access-date=27 March 2013 }}</ref> returns the value [https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/undefined <code>undefined</code>] In Java and C#, not permitted if function is value-returning |- | [[BASIC]] | <syntaxhighlight lang="qbasic">RETURN</syntaxhighlight> | |- | [[Lisp (programming language)|Lisp]] | <syntaxhighlight lang="lisp">(return value)</syntaxhighlight> | Last statement value |- | [[Perl]], [[Ruby (programming language)|Ruby]] | <syntaxhighlight lang="perl">return @values; return $value; return;</syntaxhighlight> or a contextual return sequence | Last statement value |- | [[PL/I]] | return(expression); return; | [[Undefined behavior]] if procedure is declared as returning a value |- | [[Python (programming language)|Python]] | <syntaxhighlight lang="python">return value</syntaxhighlight> | <code>None</code><ref name=python/> |- | [[Smalltalk]] | <syntaxhighlight lang="smalltalk">^ value</syntaxhighlight> | |- | [[Tcl]] | <syntaxhighlight lang="Tcl" class="nowrap">return return $value return -code error "Error message"</syntaxhighlight> or some more complicated combination of options | Last statement value |- | [[Visual Basic .NET]] | <syntaxhighlight lang="vbnet">Return value</syntaxhighlight> | |- | [[Windows PowerShell]] | <syntaxhighlight lang="ps1">return value;</syntaxhighlight> | Object |- | [[x86 assembly]] | <syntaxhighlight lang="asm">ret</syntaxhighlight> | Contents of eax register (by conventions) |} In some [[assembly language]]s, for example that for the [[MOS Technology 6502]], the mnemonic "RTS" (ReTurn from Subroutine) is used. == Multiple return statements {{anchor|Multiple}} == {{further|Early exit}} 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]] make sure each function has a single entry and a single exit (SESE). It has thus been argued<ref>{{cite web |last=Swartz |first=Fred |url=https://www.fredosaurus.com/notes-cpp/functions/return.html |title=C++ Notes: Function return Statement |archive-url=https://web.archive.org/web/20070103043830/https://www.fredosaurus.com/notes-cpp/functions/return.html |archive-date=3 January 2007 |url-status=dead}}</ref> 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]] 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 (computer scientist)|David Watt]] writes that "single-entry multi-exit control flows are often desirable". Using Tennent's framework notion of [[S-algol|sequencer]], 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 statement|breaks]] 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]]". Watt also examines how exception sequencers differ from escape and jump sequencers; for details on this see the article on structured programming.<ref>{{cite book |first1=David Anthony |last1=Watt |first2=William |last2=Findlay |title=Programming Language Design Concepts |date=2004 |publisher=John Wiley & Sons |isbn=978-0-470-85320-7 |pages=215–221 }}</ref> According to empirical studies cited by [[Eric S. Roberts]], student programmers had difficulty formulating correct solutions for several simple problems in a language like Pascal, which does not 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.<ref>{{cite journal |last=Roberts |first=E. |date=March 1995 |title=Loop Exits and Structured Programming: Reopening the Debate |journal=ACM SIGCSE Bulletin |volume=27 |issue=1 |pages=268–272 |doi=10.1145/199691.199815 |doi-access=free }}</ref> Others, including [[Kent Beck]] and [[Martin Fowler (software engineer)|Martin Fowler]] argue that one or more [[Guard (computer science)|guard clauses]]—conditional "early exit" return statements near the beginning of a function—often make a function easier to read than the alternative.<ref>{{cite book |author1=Martin Fowler |author2=Kent Beck |author3=John Brant |author4=William Opdyke |author5=Don Roberts |url=https://books.google.com/books?id=HmrDHwgkbPsC |title=Refactoring: Improving the Design of Existing Code (Google eBook) |date=2012 |pages=237,250 |publisher=Addison-Wesley |isbn=9780133065268 |quote=... one exit point mentality ... I don't follow the rule about one exit point from a method.}}</ref><ref> {{cite book |author=Kent Beck |url=https://books.google.com/books?id=xLyXPCxBhQUC |title=Implementation Patterns |date=2007 |chapter=7: Behavior | publisher=Pearson Education | isbn=9780132702553 |at=section "Guard Clause"}}</ref><ref>{{cite web |url=http://www.javapractices.com/topic/TopicAction.do?Id=114 |title=Multiple return statements |website=Java Practices}}</ref><ref>{{cite web |author=Fred Swartz |url=http://www.leepoint.net/JavaBasics/methods/method-commentary/methcom-30-multiple-return.html |title=Return statements and the single exit fantasy |archive-url=https://web.archive.org/web/20200223081346/http://leepoint.net/JavaBasics/methods/method-commentary/methcom-30-multiple-return.html |archive-date=2020-02-23 |url-status=dead}}</ref> 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 [[Tracing (software)|trace]] statement) might not be performed in all cases. Languages without a return statement, such as standard Pascal 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 (computer science)|record]] or [[Struct (C programming language)|struct]] types) to simplify their [[compiler]]s. In [[Java (programming language)|Java]]—and similar languages modeled after it, like [[JavaScript]]—it is possible to execute code even after return statement, because the ''finally'' block of a [[Try-catch block|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.<ref>{{cite web |url=http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html |title=The finally Block |work=The Java Tutorials}}</ref> ==Yield statements== {{main|Coroutines}} Cousin to return statements are [[yield statement]]s: where a return causes a ''sub''routine to ''terminate,'' a yield causes a [[coroutine|''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== {{main|Calling convention}} A number of possible call/return sequences are possible depending on the hardware instruction set, including the following: # The <code>CALL</code> instruction pushes address of the <em>next</em> instruction on the stack and branches to the specified address. The <code>RETURN</code> instruction pops the return address from the stack into the instruction pointer and execution resumes at that address. (Examples: [[x86]], [[PDP-11]]) In architectures such as the [[Motorola 96000]], the stack area may be allocated in a separate address space, which is called 'Stack Memory Space',<ref>{{cite web |url=https://www.nxp.com/docs/en/user-guide/DSP96002UM.pdf#page=27 |title=DSP96002 32-BIT DIGITAL SIGNAL PROCESSOR USER'S MANUAL |page=27(3 - 4) |accessdate=2023-12-24}}</ref> distinct from the main memory address space.<ref>{{cite web |url=https://www.nxp.com/docs/en/user-guide/DSP96002UM.pdf#page=50 |title=DSP96002 32-BIT DIGITAL SIGNAL PROCESSOR USER'S MANUAL |page=50(4 - 11) |accessdate=2023-12-24}}</ref> The [[NEC μPD7720]] also features a stack with its own separate address space.<ref>{{Cite web |url=https://www.datasheetarchive.com/datasheet?id=71b7ef54b1f0964332c3db2035de7589c6d319&type=M&term=upd7720 |title=μPD77C20A, 7720A, 77P20 Digital Signal Processor |page=4(3a-4) |accessdate=2023-12-25}}</ref> # The <code>CALL</code> instruction places address of the <em>next</em> instruction in a register and branches to the specified address. The <code>RETURN</code> instruction sequence places the return address from the register into the instruction pointer and execution resumes at that address. (Examples: [[IBM System/360]] and successors through [[z/Architecture]], most [[reduced instruction set computing|RISC]] architectures) # The <code>CALL</code> instruction places address of the <em>next</em> (or <em>current</em>) instruction in the storage location at the call address and branches to the specified address+1. The <code>RETURN</code> instruction sequence branches to the return address by an [[indirection|indirect]] jump to the first instruction of the subroutine. (Examples: [[IBM 1130]], [[SDS 9 Series|SDS 9XX]], [[PDP-8]]) ==See also== *[[Return type]] *[[Exit status]] ==Notes== {{Notelist}} ==References== {{Reflist}} {{DEFAULTSORT:Return Statement}} [[Category:BASIC commands]] [[Category:Subroutines]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Anchor
(
edit
)
Template:Cite book
(
edit
)
Template:Cite journal
(
edit
)
Template:Cite report
(
edit
)
Template:Cite web
(
edit
)
Template:Efn
(
edit
)
Template:Further
(
edit
)
Template:Main
(
edit
)
Template:More citations needed
(
edit
)
Template:Notelist
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)