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
(section)
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!
== 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>
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)