Incomputer programming, aparameter or aformal argument is a special kind ofvariable used in asubroutine to refer to one of the pieces of data provided as input to the subroutine.[a][1] These pieces of data are the values[2][3][4] of thearguments (often calledactual arguments oractual parameters) with which the subroutine is going to be called/invoked. An ordered list of parameters is usually included in thedefinition of a subroutine, so that, each time the subroutine is called, its arguments for that call are evaluated, and the resulting values can be assigned to the corresponding parameters.
Unlikeargument in usual mathematical usage, theargument in computer science is the actual input expression passed/supplied to a function, procedure, or routine in the invocation/call statement, whereas theparameter is the variable inside the implementation of the subroutine. For example, if one defines theadd
subroutine asdef add(x, y): return x + y
, thenx, y
are parameters, while if this is called asadd(2, 3)
, then2, 3
are the arguments. Variables (and expressions thereof) from the calling context can be arguments: if the subroutine is called asa = 2; b = 3; add(a, b)
then thevariablesa, b
are the arguments, not thevalues2, 3
. See theParameters and arguments section for more information.
The semantics for how parameters can be declared and how the (value of) arguments are passed to the parameters of subroutines are defined by theevaluation strategy of the language, and the details of how this is represented in any particular computer system depend on thecalling convention of that system. In the most common case,call by value, a parameter acts within the subroutine as a new local variable initialized to the value of the argument (alocal (isolated) copy of the argument if the argument is a variable), but in other cases, e.g.call by reference, the argument variable supplied by the caller can be affected by actions within the called subroutine.
The following program in theC programming language defines a function that is named "SalesTax" and has one parameter named "price". The type of price is "double" (i.e. adouble-precision floating point number). The function's return type is also a double.
doubleSalesTax(doubleprice){return0.05*price;}
After the function has been defined, it can be invoked as follows:
SalesTax(10.00);
In this example, the function has been invoked with theargument 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 {}.0.05 * price
indicates that the first thing to do is multiply 0.05 by the value of price, which gives 0.50.return
means the function will produce the result of0.05 * price
. Therefore, the final result (ignoring possible round-off errors one encounters with representing decimal fractions as binary fractions) is 0.50.
The termsparameter andargument may have different meanings in different programming languages. Sometimes they are used interchangeably, and the context is used to distinguish the meaning. The termparameter (sometimes calledformal parameter) is often used to refer to the variable as found in the functiondeclaration, whileargument (sometimes calledactual parameter) refers to the actual input supplied at a function call statement. For example, if one defines a function asdef f(x): ...
, thenx
is the parameter, and if it is called bya = ...; f(a)
thena
is the argument. A parameter is an (unbound) variable, while the argument can be aliteral 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,f(2)
anda = 2; f(a)
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.[5] The specification forpass-by-reference orpass-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 definitionf(x) = x*x
the variablex is a parameter; in the function callf(2)
the value 2 is the argument of the function. Loosely, a parameter is a type, and an argument is an instance.
A parameter is an intrinsic property of the procedure, included in its definition. For example, in many languages, a procedure to add two supplied integers together and calculate the sum would need two parameters, one for each integer. In general, a procedure may be defined with any number of parameters, or no parameters at all. If a procedure has parameters, the part of its definition that specifies the parameters is called itsparameter list.
By contrast, the arguments are the expressions[6] 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 theargument 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 subroutine is called atrun-time. When discussing code that is calling into a subroutine, any values or references passed into the subroutine are the arguments, and the place in the code where these values or references are given is theparameter list. When discussing the code inside the subroutine definition, the variables in the subroutine'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:
voidThreadFunction(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.}
To better understand the difference, consider the following function written inC:
intSum(intaddend1,intaddend2){returnaddend1+addend2;}
The functionSum has two parameters, namedaddend1 andaddend2. It adds the values passed into the parameters, and returns the result to the subroutine's caller (using a technique automatically supplied by the C compiler).
The code which calls theSum function might look like this:
intvalue1=40;intvalue2=2;intsum_value=Sum(value1,value2);
The variablesvalue1 andvalue2 are initialized with values.value1 andvalue2 are both arguments to thesum function in this context.
At runtime, the values assigned to these variables are passed to the functionSum as arguments. In theSum function, the parametersaddend1 andaddend2 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 variablesum_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 aruntime error.
Within theEiffel software development method and language, the termsargument andparameter have distinct uses established by convention. The termargument is used exclusively in reference to a routine's inputs,[7] and the termparameter is used exclusively in type parameterization forgeneric classes.[8]
Consider the following routine definition:
sum(addend1:INTEGER;addend2:INTEGER):INTEGERdoResult:=addend1+addend2end
The routinesum
takes two argumentsaddend1
andaddend2
, which are called the routine'sformal arguments. A call tosum
specifiesactual arguments, as shown below withvalue1
andvalue2
.
sum_value:INTEGERvalue1:INTEGER=40value2:INTEGER=2…sum_value:=sum(value1,value2)
Parameters are also thought of as eitherformal oractual.Formal generic parameters are used in the definition of generic classes. In the example below, the classHASH_TABLE
is declared as a generic class which has two formal generic parameters,G
representing data of interest andK
representing the hash key for the data:
classHASH_TABLE[G,K->HASHABLE]…
When a class becomes a client toHASH_TABLE
, the formal generic parameters are substituted withactual generic parameters in ageneric derivation. In the following attribute declaration,my_dictionary
is to be used as a character string baseddictionary. As such, both data and key formal generic parameters are substituted with actual generic parameters of typeSTRING
.
my_dictionary:HASH_TABLE[STRING,STRING]
Instrongly typed programming languages, each parameter'stype must be specified in the procedure declaration. Languages usingtype 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 subroutine has no parameters; in formaltype theory, such functions take an empty parameter list (whose type is notvoid, but ratherunit).
The exact mechanism for assigning arguments to parameters, calledargument passing, depends upon theevaluation strategy used for that parameter (typicallycall by value), which may be specified using keywords.
Some programming languages such asAda,C++,Clojure,[citation needed]Common Lisp,[9]Fortran 90,[10]Python,Ruby,Tcl, andWindows PowerShell[citation needed] allow for adefault argument to be explicitly or implicitly given in a subroutine's declaration. This allows the caller to omit that argument when calling the subroutine. 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 asOptional) then the language provides a well-known value (such asnull,Empty, zero, an empty string, etc.) if a value is not provided by the caller.
PowerShell example:
functiondoc($g=1.21){"$g gigawatts? $g gigawatts? Great Scott!"}
PS >doc1.21 gigawatts? 1.21 gigawatts? Great Scott!PS >doc8888 gigawatts? 88 gigawatts? Great Scott!
Default arguments can be seen as a special case of the variable-length argument list.
Some languages allow subroutines to be defined to accept avariable number of arguments. For such languages, the subroutines must iterate through the list of arguments.
PowerShell example:
functionmarty{$args|foreach{"back to the year $_"}}
PS >marty1985back to the year 1985PS >marty201519851955back to the year 2015back to the year 1985back to the year 1955
Some programming languages—such asAda andWindows PowerShell—allow subroutines to havenamed parameters. This allows the calling code to be moreself-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:
functionjennifer($adjectiveYoung,$adjectiveOld){"Young Jennifer: I'm $adjectiveYoung!""Old Jennifer: I'm $adjectiveOld!"}
PS >jennifer'fresh''experienced'Young Jennifer: I'm fresh!Old Jennifer: I'm experienced!PS >jennifer-adjectiveOld'experienced'-adjectiveYoung'fresh'Young Jennifer: I'm fresh!Old Jennifer: I'm experienced!
Inlambda calculus, each function has exactly one parameter. What is thought of as functions with multiple parameters is usually represented in lambda calculus as a function which takes the first argument, and returns a function which takes the rest of the arguments; this is a transformation known ascurrying. Some programming languages, likeML andHaskell, follow this scheme. In these languages, every function has exactly one parameter, and what may look like the definition of a function of multiple parameters, is actuallysyntactic sugar for the definition of a function that returns a function, etc.Function application isleft-associative in these languages as well as in lambda calculus, so what looks like an application of a function to multiple arguments is correctly evaluated as the function applied to the first argument, then the resulting function applied to the second argument, etc.
Anoutput parameter, also known as anout parameter orreturn parameter, is a parameter used for output, rather than the more usual use for input. Usingcall 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++,[b] while other languages have built-in support for output parameters. Languages with built-in support for output parameters includeAda[11] (seeAda subprograms),Fortran (sinceFortran 90; seeFortran "intent"), various procedural extensions toSQL, such asPL/SQL (seePL/SQL functions)[12] andTransact-SQL,C#[13] and the.NET Framework,[14]Swift,[15] and the scripting languageTScript (seeTScript function declarations).
More precisely, one may distinguish three types of parameters orparameter modes:input parameters,output parameters, andinput/output parameters; these are often denotedin
,out
, andin out
orinout
. 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, inAda 83 output parameters can only be assigned to, not read, even after assignment (this was removed inAda 95 to remove the need for an auxiliary accumulator variable). These are analogous to the notion of avalue 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 asvoid f(out int x)
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:
TextExtent(WStringtext,Fontfont:Integerwidth,Integerheight)
Parameter modes are a form ofdenotational semantics, stating the programmer's intent and allowing compilers to catch errors and apply optimizations – they do not necessarily implyoperational 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 theAda '83 Rationale, which emphasizes that the parameter mode is abstracted from which parameter passing mechanism (by reference or by copy) is actually implemented.[11] For instance, while in C# input parameters (default, no keyword) are passed by value, and output and input/output parameters (out
andref
) are passed by reference, in PL/SQL input parameters (IN
) are passed by reference, and output and input/output parameters (OUT
andIN OUT
) are by default passed by value and the result copied back, but can be passed by reference by using theNOCOPY
compiler hint.[16]
A syntactically similar construction to output parameters is to assign thereturn value to a variable with the same name as the function. This is found inPascal andFortran 66 andFortran 77, as in this Pascal example:
functionf(x,y:integer):integer;beginf:=x+y;end;
This is semantically different in that when called, the function is simply evaluated – it is not passed a variable from the callingscope to store the output in.
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 thesemipredicate problem of returning both a value and an error status – seeSemipredicate problem: Multivalued return.
For example, to return two variables from a function in C, one may write:
intwidthintheight;F(x,&width,&height);
wherex
is an input parameter andwidth
andheight
are output parameters.
A common use case in C and related languages is forexception 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 theTryParse
method in .NET, especially C#, which parses a string into an integer, returningtrue
on success andfalse
on failure. This has the following signature:[17]
publicstaticboolTryParse(strings,outintresult)
and may be used as follows:
intresult;if(!Int32.TryParse(s,result)){// exception handling}
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.
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.[18] 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 preventfunction 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:
Objectobj=G(y,F(x));
when written with output and input/output parameters instead becomes (forF
it is an output parameter, forG
an input/output parameter):
Objectobj;F(x,&obj);G(y,&obj);
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:
Objectobj;G(y,F(x,&obj));
There are various alternatives to the use cases of output parameters.
For returning multiple values from a function, an alternative is to return atuple. Syntactically this is clearer if automatic sequence unpacking andparallel assignment can be used, as inGo or Python, such as:
deff():return1,2a,b=f()
For returning a value of one of several types, atagged union can be used instead; the most common cases arenullable types (option types), 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:
result=parse(s)ifresultisNone:# exception handling
or, more idiomatically:
try:result=parse(s)exceptParseError:# exception handling
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.[13] For example, given a structure encapsulating width and height, one can write:
WidthHeightwidth_and_height=F(x);
In object-oriented languages, instead of using input/output parameters, one can often usecall by sharing, passing a reference to an object and then mutating the object, though not changing which object the variable refers to.[18]
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.