Parameter (computer programming): Difference between revisions

Content deleted Content added
m Reverted edit by R. S. Shaw (talk) to last version by HeyElliott
Argument passing: exact adds no value
 
(27 intermediate revisions by 13 users not shown)
Line 1:
{{Short description |AnVariable that represents inputan providedargument to a function/subroutine}}
{{Other uses |Parameter (disambiguation)}}
In [[computer programming]], a '''parameter''' or, a.k.a. '''formal argument''', is a special kind of [[Variable (computer science)|variable]] usedthat inrepresents aan [[subroutine]]argument, toa.k.a. referactual toargument, one of the pieces of data provided as input to the subroutinea.k.a.{{efn|1=In thisactual articleparameter, the term "subroutine" refers to anya subroutine-like[[Function construct,(computer which have different names and slightly different meanings depending on the [[programming language)|function]] being discussedcall.}}<ref name="Oracle">{{cite web | title=Passing Information to a Method or a Constructor (The Java™ Tutorials > Learning the Java Language > Classes and Objects) | website=Oracle.comThe Java™ Tutorials | url=https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html | access-date=2021-09-09 | quote=Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.}}</ref> These pieces of data are the values<ref>{{cite book|last1=Prata|first1=Stephen|title=C primer plus|date=2004|publisher=Sams|isbn=978-0-672-32696-7|pages=276–277|edition=5th}}</ref><ref>{{cite web|title=Working Draft, Standard for Programming Language C++|url=http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf|archive-url=https://web.archive.org/web/20051214034042/http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf|url-status=dead|archive-date=December 14, 2005|website=www.openOpen Standards |date=2005-std.org10-19 |access-date=1 January 2018}}</ref><ref>{{cite web|last1=Gordon|first1=Aaron|title=Subprograms and Parameter Passing|url=http://rowdysites.msudenver.edu/~gordona/cs3210/lects/lect10.html|website=rowdysites.msudenver.edu/~gordona|access-date=1 January 2018|archive-url=https://web.archive.org/web/20180101140104/http://rowdysites.msudenver.edu/~gordona/cs3210/lects/lect10.html|archive-date=1 January 2018|url-status=dead}}</ref> of theA function'''arguments''' (often called ''actual arguments'' or ''actual parameters'') with which the subroutine is going to be called/invoked. An ordered list of parameters is usually included in thes [[function signature|definition of a subroutinesignature]], sodefines that,its eachparameters. timeA thecall subroutineinvocation isinvolves called,evaluating itseach argumentsargument forexpression thatof a call areand evaluated, andassociating the resultingresult values can be assigned towith the corresponding parametersparameter.
 
Unlike [[Argument of a function|''argument'']] in usual mathematical usage, the ''argument'' in computer science is the actual input expression passed/supplied to a function, procedure, or routine in the invocation/call statement, whereas the ''parameter'' is the variable inside the implementation of the subroutine. For example, ifconsider one defines the <code>add</code> subroutine asfunction <code>def add(x, y): return x + y</code>,. thenVariables <code>x,</code> and <code>y</code> are parameters,. whileFor if this is called ascall <code>add(2, 3)</code>, thenthe expressions <code>2,</code> and <code>3</code> are the arguments. NoteFor that variables (and expressions thereof) from the calling context can be arguments: if the subroutine is called ascall <code>a = 2; b = 3; add(a+1, b+2)</code> then, the ''variables''arguments are <code>a, b+1</code> are the arguments, not the ''values''and <code>b+2, 3</code>. See the [[#Parameters and arguments|Parameters and arguments]] section for more information.
 
TheParameter semanticspassing foris howdefined parametersby cana beprogramming declared and how the (value of) arguments are passed to the parameters of subroutines are defined by thelanguage. [[evaluationEvaluation strategy]] ofdefines the language,semantics and the details offor how thisparameters iscan representedbe indeclared anyand particularhow computerarguments systemare dependpassed onto the [[calling convention]] of thata systemfunction. InGenerally, the most common case,with [[call by value]], a parameter acts within the subroutine aslike a new, [[local variable]] initialized to the value of the argument. (aIf [[Localthe variable|local]]argument (isolated)is copya ofvariable, the argumentfunction ifcannot modify the argument isstate abecause variable),the butparameter inis othera cases, e.gcopy. With [[call by reference]], which requires the argument variableto suppliedbe bya variable, the callerparameter canis bean affectedalias by actions withinof the called subroutineargument.
 
==Example==
The following program in the [[C (programming language)|C]] programming[[source languagecode]] defines a function thatnamed is{{code named "|SalesTax"}} and haswith one parameter named "{{code |price".}}; Theboth typetyped of{{code price|double}}. isFor "double"call {{code |SalesTax(i10.e00)}}, the argument {{code|10.00}} ais passed to the function as the [[floating point|doubleDouble-precision floating -point format |double]] number).value The10 function'sand returnassigned typeto isparameter alsovariable a{{code double|price}}, and the function returns 0.5.
 
<syntaxhighlight lang="c">
double SalesTax(double price)
Line 15 ⟶ 16:
}
</syntaxhighlight>
 
After the function has been defined, it can be invoked as follows:
<syntaxhighlight lang="c">
SalesTax(10.00);
</syntaxhighlight>
 
In this example, the function has been invoked with the ''argument'' 10.00. When this happens, 10.00 will be assigned to price, and the function begins calculating its result. The steps for producing the result are specified below, enclosed in {}. <code>0.05 * price</code> indicates that the first thing to do is multiply 0.05 by the value of price, which gives 0.50. <code>return</code> means the function will produce the result of <code>0.05 * price</code>. Therefore, the final result (ignoring possible round-off errors one encounters with representing decimal fractions as binary fractions) is 0.50.
 
== Parameters and arguments ==
The terms ''parameter'' and ''argument'' may have different meanings in different programming languages. Sometimes they are used interchangeably, and the context is used to distinguish the meaning. The term ''parameter'' (sometimes called ''formal parameter'') is often used to refer to the variable as found in the function definition[[Declaration (computer programming)|declaration]], while ''argument'' (sometimes called ''actual parameter'') refers to the actual input supplied at a function call statement. For example, if one defines a function as <code>def f(x): ...</code>, then <code>x</code> is the parameter, and if it is called by <code>a = ...; f(a)</code> then <code>a</code> is the argument. A parameter is an (unbound) variable, while the argument can be a [[Literal (computer programming)|literal]] or variable or more complex expression involving literals and variables. In case of call by value, what is passed to the function is the value of the argument – for example, <code>f(2)</code> and <code>a = 2; f(a)</code> are equivalent calls – while in call by reference, with a variable as argument, what is passed is a reference to that variable - even though the syntax for the function call could stay the same.<ref>{{Cite web|url=https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/passing-arguments-by-value-and-by-reference|title=Passing Arguments by Value and by Reference (Visual Basic)|last=Dollard|first=Kathleen|website=docs.microsoft.comMicrosoft Learn |language=en-us|access-date=2018-10-27}}</ref> The specification for [[Call_by_reference|pass-by-reference]] or [[Call by value|pass-by-value]] would be made in the function declaration and/or definition.
 
Parameters appear in procedure definitions; arguments appear in procedure calls. In the function definition <code>f(x) = x*x</code> the variable <var>x</var> is a parameter; in the function call <code>f(2)</code> the value 2 is the argument of the function. Loosely, a parameter is a type, and an argument is an instance.
Line 32 ⟶ 26:
By contrast, the arguments are the expressions<ref>{{Cite web|url=http://crasseux.com/books/ctutorial/Actual-parameters-and-formal-parameters.html|title=The GNU C Programming Tutorial|website=crasseux.com|language=en|access-date=2018-10-27}}</ref> supplied to the procedure when it is called, usually one expression matching one of the parameters. Unlike the parameters, which form an unchanging part of the procedure's definition, the arguments may vary from call to call. Each time a procedure is called, the part of the procedure call that specifies the arguments is called the ''argument list''.
 
Although parameters are also commonly referred to as arguments, arguments are sometimes thought of as the actual values or references assigned to the parameter variables when the subroutinefunction is called at [[Run time (program lifecycle phase)|run-time]]. When discussing code that is calling into a subroutinefunction, any values or references passed into the subroutinefunction are the arguments, and the place in the code where these values or references are given is the ''parameter list''. When discussing the code inside the subroutinefunction definition, the variables in the subroutinefunction's parameter list are the parameters, while the values of the parameters at runtime are the arguments. For example, in C, when dealing with threads it is common to pass in an argument of type void* and cast it to an expected type:
 
<syntaxhighlight lang="c">
Consider the following [[C (programming language)|C]] function, ''Sum'', which has two parameters, ''addend1'' and ''addend2''. It adds the values passed into the parameters, and returns the result to the function's caller.
void ThreadFunction(void* pThreadArgument)
{
// Naming the first parameter 'pThreadArgument' is correct, rather than
// 'pThreadParameter'. At run time the value we use is an argument. As
// mentioned above, reserve the term parameter for when discussing
// subroutine definitions.
}
</syntaxhighlight>
 
To better understand the difference, consider the following function written in [[C (programming language)|C]]:
<syntaxhighlight lang="c">
int Sum(int addend1, int addend2)
Line 51 ⟶ 37:
</syntaxhighlight>
 
The functionfollowing is an example of calling ''Sum''. hasThe twovariables parameters,''value1'' namedand ''addend1value2'' are initialized and then passed to ''addend2Sum'' as the arguments. ItAt addsruntime, the values assigned to these variables are passed intoto ''Sum''. In ''Sum'', the parameters ''addend1'' and ''addend2'' are evaluated, yielding the arguments 40 and returns2, respectively. The values of the arguments are added, and the result is returned to the subroutine's caller, (usingwhere ait techniqueis automaticallyassigned supplied byto the Cvariable compiler)''sum_value''.
 
The code which calls the ''Sum'' function might look like this:
<syntaxhighlight lang="c">
int value1 = 40;
Line 59 ⟶ 44:
int sum_value = Sum(value1, value2);
</syntaxhighlight>
The variables ''value1'' and ''value2'' are initialized with values. ''value1'' and ''value2'' are both arguments to the ''sum'' function in this context.
 
At runtime, the values assigned to these variables are passed to the function ''Sum'' as arguments. In the ''Sum'' function, the parameters ''addend1'' and ''addend2'' are evaluated, yielding the arguments 40 and 2, respectively. The values of the arguments are added, and the result is returned to the caller, where it is assigned to the variable ''sum_value''.
 
Because of the difference between parameters and arguments, it is possible to supply inappropriate arguments to a procedure. The call may supply too many or too few arguments; one or more of the arguments may be a wrong type; or arguments may be supplied in the wrong order. Any of these situations causes a mismatch between the parameter and argument lists, and the procedure will often return an unintended answer or generate a [[runtime error]].
Line 103 ⟶ 85:
In [[strongly typed programming language]]s, each parameter's [[Datatype|type]] must be specified in the procedure declaration. Languages using [[type inference]] attempt to discover the types automatically from the function's body and usage. Dynamically typed programming languages defer type resolution until run-time. Weakly typed languages perform little to no type resolution, relying instead on the programmer for correctness.
 
Some languages use a special keyword (e.g. ''void'') to indicate that the subroutinefunction has no parameters; in formal [[type theory]], such functions take an empty parameter list (whose type is not ''void'', but rather ''[[unit type|unit]]'').
 
== Argument passing ==
The exact mechanism for assigning arguments to parameters, called ''argument passing'', depends upon the [[evaluation strategy]] used for that parameter (typically [[call by value]]), which may be specified using keywords.
 
=== Default arguments ===
Some programming languages such as [[Ada (programming language)|Ada]], [[C++]], [[Clojure]],{{Citation needed|date=June 2021}} [[Common Lisp]],<ref>{{Cite web|title=Functions|url=https://gigamonkeys.com/book/functions.html|access-date=2021-06-02|website=gigamonkeys.com}}</ref> [[Fortran 90]],<ref>{{Cite web|title=optional arguments|url=http://www.netlib.org/ccm/page/api/optional.html|access-date=2021-06-02|website=www.netlib.org}}</ref> [[Python (programming language)|Python]], [[Ruby (programming language)|Ruby]], [[Tcl (programming language)|Tcl]], and [[Windows PowerShell]]{{Citation needed|date=June 2021}} allow for a [[default argument]] to be explicitly or implicitly given in a subroutinefunction's declaration. This allows the caller to omit that argument when calling the subroutinefunction. If the default argument is explicitly given, then that value is used if it is not provided by the caller. If the default argument is implicit (sometimes by using a keyword such as ''Optional'') then the language provides a well-known value (such as ''[[Null pointer|null]]'', ''Empty'', zero, an empty string, etc.) if a value is not provided by the caller.
 
PowerShell example:
Line 127 ⟶ 109:
 
=== Variable-length parameter lists ===
Some languages allow subroutinesfunctions to be defined to accept a [[Variadic function|variable number of arguments]]. For such languages, the subroutinesfunctions must iterate through the list of arguments.
 
PowerShell example:
Line 146 ⟶ 128:
 
=== Named parameters ===
Some programming languages—such as [[Ada (programming language)|Ada]] and [[Windows PowerShell]]—allow subroutinesfunctions to have [[named parameter]]s. This allows the calling code to be more [[self-documenting]]. It also provides more flexibility to the caller, often allowing the order of the arguments to be changed, or for arguments to be omitted as needed.
 
PowerShell example:
Line 209 ⟶ 191:
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 booleanBoolean 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)
Line 267 ⟶ 249:
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);