Parameter (computer programming): Difference between revisions

Content deleted Content added
Example: Remove fluff
Argument passing: exact adds no value
 
(8 intermediate revisions by 3 users not shown)
Line 1:
{{Short description |RepresentationVariable ofthat represents an argument into a function definition}}
{{Other uses |Parameter (disambiguation)}}
In [[computer programming]], a '''parameter''', a.k.a. '''formal argument''', is a [[Variable (computer science)|variable]] that represents an argument, a.k.a. actual argument, a.k.a. actual parameter, to a [[subroutine]]Function call.{{efn|1=In(computer this article, the term "subroutine" refers to any subroutine-like construct, 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 (Learning the Java Language > Classes and Objects) | website=The 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><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=Open Standards |date=2005-10-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>. A function's [[function signature|signature]] defines its parameters. A call invocation involves evaluating each argument expression of a call and associating the result with the corresponding parameter.
 
For example, consider subroutinefunction <code>def add(x, y): return x + y</code>. Variables <code>x</code> and <code>y</code> are parameters. For call <code>add(2, 3)</code>, the expressions <code>2</code> and <code>3</code> are arguments. For call <code>add(a+1, b+2)</code>, the arguments are <code>a+1</code> and <code>b+2</code>.
 
Parameter passing is defined by a programming language. [[Evaluation strategy]] defines the semantics for how parameters can be declared and how arguments are passed to a subroutinefunction. Generally, with [[call by value]], a parameter acts like a new, [[local variable]] initialized to the value of the argument. If the argument is a variable, the subroutinefunction cannot modify the argument state because the parameter is a copy. With [[call by reference]], which requires the argument to be a variable, the parameter is an alias of the argument.
 
==Example==
The following program[[C (programming language)|C]] [[source code]] defines a function named {{code |SalesTax}} with one parameter named {{code |price}}; both typed {{code |double}}. For call {{code |SalesTax(10.00)}}, the argument {{code|10.00}} is passed to the function as the [[Double-precision floating-point format |double]] value 10 and assigned to parameter variable {{code |price}}, and the function returns 0.5.
 
<syntaxhighlight lang="c">
Line 16:
}
</syntaxhighlight>
 
For call {{code|SalesTax(10.00)}}, the argument {{code|10.00}} is assigned to parameter variable {{code|price}}, the function is executed and returns {{code|0.50}}.
 
== Parameters and arguments ==
Line 28 ⟶ 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 47 ⟶ 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 55 ⟶ 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 99 ⟶ 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 123 ⟶ 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 142 ⟶ 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 263 ⟶ 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);