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
Parameter (computer programming)
(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!
==Output parameters== An '''output parameter''', also known as an '''out parameter''' or '''return parameter''', is a parameter used for output, rather than the more usual use for input. Using [[call by reference]] parameters, or call by value parameters where the value is a reference, as output parameters is an idiom in some languages, notably C and C++,{{efn|C and C++ are call by value, but if type is a reference (a C/C++ pointer or C++ reference), then setting the value of the reference can be used to produce call by reference style behavior.}} while other languages have built-in support for output parameters. Languages with built-in support for output parameters include [[Ada (programming language)|Ada]]<ref name=ada>[http://archive.adaic.com/standards/83rat/html/ratl-08-02.html 8.2 Parameter Modes], "[http://archive.adaic.com/standards/83rat/html/Welcome.html Rationale for the Design of the Adaยฎ Programming Language]"</ref> (see [[b:Ada Programming/Subprograms|Ada subprograms]]), [[Fortran]] (since [[Fortran 90]]; see [[b:Fortran/Fortran procedures and functions#Intent|Fortran "intent"]]), various procedural extensions to [[SQL]], such as [[PL/SQL]] (see [[PL/SQL#Functions|PL/SQL functions]])<ref>[http://docs.oracle.com/cd/B10500_01/appdev.920/a96624/08_subs.htm#895 8. PL/SQL Subprograms: Specifying Subprogram Parameter Modes]</ref> and [[Transact-SQL]], [[C Sharp (programming language)|C#]]<ref name=hallam>{{cite web |title=Why does C# have both 'ref' and 'out'? |author=Peter Hallam |url=http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx |archive-url=https://web.archive.org/web/20110926113834/http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx |archive-date=2011-09-26}}</ref> and the [[.NET Framework]],<ref>[http://msdn.microsoft.com/en-us/library/system.data.parameterdirection.aspx ParameterDirection Enumeration]</ref> [[Swift (programming language)|Swift]],<ref>[https://docs.swift.org/swift-book/LanguageGuide/Functions.html Functions โ The Swift Programming Language (Swift 4.2)]</ref> and the scripting language [[TScript]] (see [[TScript#Function declarations|TScript function declarations]]). More precisely, one may distinguish three types of parameters or '''parameter modes''': ''{{visible anchor|input parameter}}s'', ''output parameters,'' and ''{{visible anchor|input/output parameter}}s;'' these are often denoted <code>in</code>, <code>out</code>, and <code>in out</code> or <code>inout</code>. An input argument (the argument to an input parameter) must be a value, such as an initialized variable or literal, and must not be redefined or assigned to; an output argument must be an assignable variable, but it need not be initialized, any existing value is not accessible, and must be assigned a value; and an input/output argument must be an initialized, assignable variable, and can optionally be assigned a value. The exact requirements and enforcement vary between languages โ for example, in [[Ada 83]] output parameters can only be assigned to, not read, even after assignment (this was removed in [[Ada 95]] to remove the need for an auxiliary accumulator variable). These are analogous to the notion of a [[Value (computer science)|value]] in an expression being an r-value (has a value), an l-value (can be assigned), or an r-value/l-value (has a value and can be assigned), respectively, though these terms have specialized meanings in C. In some cases only input and input/output are distinguished, with output being considered a specific use of input/output, and in other cases only input and output (but not input/output) are supported. The default mode varies between languages: in Fortran 90 input/output is default, while in C# and SQL extensions input is default, and in TScript each parameter is explicitly specified as input or output. Syntactically, parameter mode is generally indicated with a keyword in the function declaration, such as <code>void f(out int x)</code> in C#. Conventionally output parameters are often put at the end of the parameter list to clearly distinguish them, though this is not always followed. TScript uses a different approach, where in the function declaration input parameters are listed, then output parameters, separated by a colon (:) and there is no return type to the function itself, as in this function, which computes the size of a text fragment: <syntaxhighlight lang="cpp"> TextExtent(WString text, Font font : Integer width, Integer height) </syntaxhighlight> Parameter modes are a form of [[denotational semantics]], stating the programmer's intent and allowing compilers to catch errors and apply optimizations โ they do not necessarily imply [[operational semantics]] (how the parameter passing actually occurs). Notably, while input parameters can be implemented by call by value, and output and input/output parameters by call by reference โ and this is a straightforward way to implement these modes in languages without built-in support โ this is not always how they are implemented. This distinction is discussed in detail in the ''Ada '83 Rationale,'' which emphasizes that the parameter mode is abstracted from which parameter passing mechanism (by reference or by copy) is actually implemented.<ref name=ada/> For instance, while in C# input parameters (default, no keyword) are passed by value, and output and input/output parameters (<code>out</code> and <code>ref</code>) are passed by reference, in PL/SQL input parameters (<code>IN</code>) are passed by reference, and output and input/output parameters (<code>OUT</code> and <code>IN OUT</code>) are by default passed by value and the result copied back, but can be passed by reference by using the <code>NOCOPY</code> compiler hint.<ref>[http://docs.oracle.com/cd/B10500_01/appdev.920/a96624/08_subs.htm#12813 8. PL/SQL Subprograms: Passing Large Data Structures with the NOCOPY Compiler Hint]</ref> A syntactically similar construction to output parameters is to assign the [[return value]] to a variable with the same name as the function. This is found in [[Pascal (programming language)|Pascal]] and [[Fortran 66]] and [[Fortran 77]], as in this Pascal example: <syntaxhighlight lang="pascal"> function f(x, y: integer): integer; begin f := x + y; end; </syntaxhighlight> This is semantically different in that when called, the function is simply evaluated โ it is not passed a variable from the calling [[scope (computer science)|scope]] to store the output in. ===Use=== The primary use of output parameters is to return multiple values from a function, while the use of input/output parameters is to modify state using parameter passing (rather than by shared environment, as in global variables). An important use of returning multiple values is to solve the [[semipredicate problem]] of returning both a value and an error status โ see [[Semipredicate problem#Multivalued return|Semipredicate problem: Multivalued return]]. For example, to return two variables from a function in C, one may write: <syntaxhighlight lang="c"> int width int height; F(x, &width, &height); </syntaxhighlight> where <code>x</code> is an input parameter and <code>width</code> and <code>height</code> are output parameters. A common use case in C and related languages is for [[exception handling]], where a function places the return value in an output variable, and returns a Boolean corresponding to whether the function succeeded or not. An archetypal example is the <code>TryParse</code> method in .NET, especially C#, which parses a string into an integer, returning <code>true</code> on success and <code>false</code> on failure. This has the following signature:<ref>[http://msdn.microsoft.com/en-us/library/f02979c7.aspx Int32.TryParse Method (String, Int32)]</ref> <syntaxhighlight lang="csharp"> public static bool TryParse(string s, out int result) </syntaxhighlight> and may be used as follows: <syntaxhighlight lang="csharp"> int result; if (!Int32.TryParse(s, result)) { // exception handling } </syntaxhighlight> Similar considerations apply to returning a value of one of several possible types, where the return value can specify the type and then value is stored in one of several output variables. ===Drawbacks=== Output parameters are often discouraged in modern programming, essentially as being awkward, confusing, and too low-level โ commonplace return values are considerably easier to understand and work with.<ref name=CA1021>[http://msdn.microsoft.com/en-us/library/ms182131.aspx CA1021: Avoid out parameters]</ref> Notably, output parameters involve functions with side effects (modifying the output parameter) and are semantically similar to references, which are more confusing than pure functions and values, and the distinction between output parameters and input/output parameters can be subtle. Further, since in common programming styles most parameters are simply input parameters, output parameters and input/output parameters are unusual and hence susceptible to misunderstanding. Output and input/output parameters prevent [[function composition (computer science)|function composition]], since the output is stored in variables, rather than in the value of an expression. Thus one must initially declare a variable, and then each step of a chain of functions must be a separate statement. For example, in C++ the following function composition: <syntaxhighlight lang="cpp"> Object obj = G(y, F(x)); </syntaxhighlight> when written with output and input/output parameters instead becomes (for <code>F</code> it is an output parameter, for <code>G</code> an input/output parameter): <syntaxhighlight lang="cpp"> Object obj; F(x, &obj); G(y, &obj); </syntaxhighlight> In the special case of a function with a single output or input/output parameter and no return value, function composition is possible if the output or input/output parameter (or in C/C++, its address) is also returned by the function, in which case the above becomes: <syntaxhighlight lang="cpp"> Object obj; G(y, F(x, &obj)); </syntaxhighlight> ===Alternatives=== There are various alternatives to the use cases of output parameters. For returning multiple values from a function, an alternative is to return a [[tuple]]. Syntactically this is clearer if automatic sequence unpacking and [[parallel assignment]] can be used, as in [[Go (programming language)|Go]] or Python, such as: <syntaxhighlight lang="python"> def f(): return 1, 2 a, b = f() </syntaxhighlight> For returning a value of one of several types, a [[tagged union]] can be used instead; the most common cases are [[nullable type]]s ([[option type]]s), where the return value can be null to indicate failure. For exception handling, one can return a nullable type, or raise an exception. For example, in Python one might have either: <syntaxhighlight lang="python"> result = parse(s) if result is None: # exception handling </syntaxhighlight> or, more idiomatically: <syntaxhighlight lang="python"> try: result = parse(s) except ParseError: # exception handling </syntaxhighlight> The micro-optimization of not requiring a local variable and copying the return when using output variables can also be applied to conventional functions and return values by sufficiently sophisticated compilers. The usual alternative to output parameters in C and related languages is to return a single data structure containing all return values.<ref name=hallam/> For example, given a structure encapsulating width and height, one can write: <syntaxhighlight lang="c"> WidthHeight width_and_height = F(x); </syntaxhighlight> In object-oriented languages, instead of using input/output parameters, one can often use [[call by sharing]], passing a reference to an object and then mutating the object, though not changing which object the variable refers to.<ref name=CA1021 />
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)