Jump to content

Parameter (computer programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 174.250.210.135 (talk) at 16:41, 30 March 2022 (Example). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, a parameter or a formal argument is a special kind of variable used in a subroutine 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 the 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 the definition 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.

Unlike 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, if one defines the add subroutine as def add(x, y): return x + y, then x, y are parameters, while if this is called as add(2, 3), then 2, 3 are the arguments. Note that variables (and expressions thereof) from the calling context can be arguments: if the subroutine is called as a = 2; b = 3; add(a, b) then the variables a, b are the arguments, not the values 2, 3. See the Parameters 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 the evaluation strategy of the language, and the details of how this is represented in any particular computer system depend on the calling 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 (a local (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.

Example

The following program in the C programming language defines a function that is named "SalesTax" and has one parameter named "price". The type of price is "double" (i.e. a double-precision floating point number). The function's return type is also a double.

double SalesTax(double price)
{
  return 0.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 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 {}. 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 of 0.05 * price. Therefore, the final result (ignoring possible round-off errors one encounters with representing decimal fractions as binary fractions) is 0.50.Parameter

A parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions.

For example:

function example(parameter) { console.log(parameter); // Output = foo } const argument = 'foo'; example(argument); Copy to Clipboard

Note the difference between parameters and arguments:

Function parameters are the names listed in the function's definition.Function arguments are the real values passed to the function.Parameters are initialized to the values of the arguments supplied.

Two kinds of parameters:

input parameters

the most common kind; they pass values into functions. Depending on programming language, input parameters can be passed several ways (e.g., call-by-value, call-by-address, call-by-reference).

output/return parameters

primarily return multiple values from a function, but not recommended since they cause confusion

See also

Difference between parameter and argument on WikipediaFunction declarationFunction expression

Found a problem with this page?Edit on GitHubSource on GitHubReport a problem with this content on GitHubWant to fix the problem yourself? See our Contribution guide.

Last modified: Jan 19, 2022, by MDN contributors

50.103.218.16 Cite error: There are <ref> tags on this page without content in them (see the help page).Accept all Save Only accept essential cookies

Back

Privacy Policy

technically necessary (1)

Essential cookies enable basic functions and are necessary for the proper functioning of the website.

Show Cookie Information

Stats (1)

Stats

Statistics Cookies collect information anonymously. This information helps us understand how our visitors use our website.

Hide Cookie Information Search results

• Cookie Monster

Cookie Monster is a blue Muppet character on the long-running PBS/HBO children's television show Sesame Street. In a song in 2004, and later in an interview

23 KB (2,687 words) - 05:58, 26 March 2022

• Cross-site scripting (section Cookie security)

access-privileges to sensitive page content, to session cookies, and to a variety of other information maintained by the browser on behalf of the user. Cross-site

46 KB (5,457 words) - 16:00, 20 February 2022

• Internet privacy (section HTTP cookies)

steal information from a user's cookies. Cookies do have benefits. One is that for websites that one frequently visits that require a password, cookies may

121 KB (15,388 words) - 18:31, 18 March 2022

• World Wide Web (category Information Age)

most operating systems). An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or simply cookie) is a small piece of data sent from

75 KB (7,875 words) - 10:58, 29 March 2022

• VPN service

ISSN 0362-4331. Retrieved 2021-12-21. "You Tossed Your Cookies But They're Still Tracking You; Here's How to Hide Your Browser Fingerprint". PCMAG. Retrieved 2021-12-21

103 KB (6,452 words) - 13:33, 26 March 2022

• Personal data (redirect from Personally identifying information)

Gender or race Web cookie In forensics, particularly the identification and prosecution of criminals, personally identifiable information is critical in establishing

38 KB (4,386 words) - 03:35, 9 March 2022

• Metasearch engine

privacy policy includes no recording of users' IP addresses, no identifying cookies, no collection of personal data, and no sharing of personal data with third

18 KB (2,313 words) - 10:29, 20 March 2022

• List of Ned's Declassified School Survival Guide characters (section Simon "Cookie" Nelson-Cook)

computer display. Occasionally, Cookie takes on a female persona named Simone, usually in order to obtain information or get into parties. This disguise

32 KB (5,177 words) - 17:07, 11 March 2022

• X Japan

year after finalizing their line-up including bassist Taiji, lead guitarist Hide and rhythm guitarist Pata. They achieved breakthrough success in 1989 with

121 KB (11,669 words) - 01:48, 23 March 2022

• List of Wild Kratts episodes

has been spotted in the desert. Villain of the week: None Animal name: Cookie, Elfis (from "Desert Elves") 137 3 "Deer Buckaroo" Chris Kratt & Chris Roy

175 KB (226 words) - 13:28, 28 March 2022



AcceptGoogle AnalyticsNameGoogle AnalyticsProviderGoogle Ireland Limited, Gordon House, Barrow Street, Dublin 4, IrelandPurpose

IMPRINT

HYBRID Software Group SARL Uhlandstraße 9 79102 Freiburg Germany Tel. +49 761 70 776 700 info-de@hybridsoftware.com

Managing Directors: Christopher Graf, Guido Van der Schueren

Amtsgericht Freiburg, HRB 70 74 74

USt-ID: DE 279 719 913 Steuernummer: 06433/41701

Responsible for the content: Christopher Graf

Concept & Design: www.gd90.de

Development: www.mrflow.de

Liability concerning the contents In our capacity as a service provider and according to Article 7, para 1 of the German Telemedia Act (TMG), we are liable for our own contents on these pages in accordance with the general legal provisions. However, in our capacity as a service provider and according to Articles 8 to 10 of the TMG, we are not obliged to monitor any transferred or stored external information or to investigate any circumstances that are indicative of an unlawful action.

Any obligations for removing or blocking the use of information in accordance with the general legal provisions shall remain unaffected. However, any liability in this respect may only be assumed from the moment of HYBRID Software actually becoming aware of a specific law infringement. As soon as we become aware of any specific law infringements, we shall undertake to remove such contents without further delay.

Liability concerning links Our range of offers comprises links to external websites of third parties, the contents of which we cannot influence. Therefore, we cannot assume any liability for such external contents. It is always the respective provider or owner of the websites linked who is responsible for the content of these pages. The pages linked were reviewed for any potential law infringements upon being linked. No unlawful content was identified upon linking the pages in question.

However, continuously reviewing the contents of the pages linked shall be deemed unacceptable without any definite indications for a law infringement being identifiable. As soon as we become aware of any law infringements, we shall undertake to remove such links without further delay.

Copyright The contents and works the site owners created on these pages are subject to the German copyright law. Any duplication, processing, distribution and any type of use outside the limits of the copyright law require the prior written approval of the respective author or site owner. HYBRID Software corporate website is property of HYBRID Software Group SARL. Any downloads and any duplications of this webpage are only permitted for private, non-commercial use.

Insofar as the contents on this page have not been created by the site owner, the copyrights of third parties will be respected. In particular, any contents of third parties will be identified as such. Notwithstanding the aforesaid, should you become aware of any copyright infringement, please let us know. Once we have been made aware of such copyright infringements, we shall undertake to remove such contents from our website without further delay.

 experience of navigation and presentation of content.If you are under 16 and wish to give consent to optional services, you must ask your legal guardians for permission.We use cookies and other technologies on our website. Some of them are essential, while others help us to improve this website and your experience. Personal data may be processed (e.g. IP addresses), for example for personalized ads and content or ad and content measurement. You can find more information about the use of your data in our privacy policy. You can revoke or adjust your selection at any time under Settings.

Why do we use cookies

• technically necessary

• Stats

• Externe Inhalte

Accept all

Save

Only accept essential cookies

Individual privacy settings

Cookie details  Privacy policy  Imprint

technically necessary (1)

Essential cookies enable basic functions and are necessary for the proper functioning of the website.

Hide Cookie Information

NameBorlabs CookieProviderEigentümer dieser Website, ImprintPurposeSpeichert die Einstellungen der Besucher, die in der Cookie Box von Borlabs Cookie ausgewählt wurden.Cookie Nameborlabs-cookieCookie runtime1 Jahr

Server log files

The website provider automatically collects and stores information that your browser automatically transmits to us in “server log files”. These are:

• Browser type and browser version • Operating system used • Referrer URL • Host name of the accessing computer • Time of the server request • support@globalgraphics.com • IP address


Get Updates Have all our status updates posted live to a Slack #channel of your choice.

Which updates would you like to receive? All status updates.Only those about certain components.

Step New Global Graphics Software Limited will share your details with Sorry™ and use them to keep you informed about changes in the availability of our service. We'll treat your information with respect, and you'll have the option to unsubscribe at any time.


These data will not be combined with data from other sources.

The basis for data processing is Art. 6 (1) (f) DSGVO. The website operator has a legitimate interest to ensure an optimized service provided free of technical errors. Therefore server log files have to be stored.

• Contact form Should you send us questions via the contact form, we will collect the data entered on the form, including the contact details you provide, to answer your question and any follow-up questions. We do not share this information without your permission.

Statutory data protection officer datenschutzbeauftragter@hybridsoftware.com

We have appointed a data protection officer for our company. Email: datenschutzbeauftragter@hybridsoftware.com

4. Data collection on our website • Cookies

Some of our web pages use cookies. Cookies do not harm your computer and do not contain any viruses. Cookies help make our website more user-friendly, efficient, and secure. Cookies are small text files that are stored on your computer and saved by your browser. • Jira Service Desk Support Portal • Email Support

Upcoming Maintenance

[Scheduled] Outage to UK services • Corporate Websites • LDK Activation Service • LDK Ordering Service • FTP Services • Online Documentation • Jira Service Desk Support Portal • Email Support

There will be a loss of service at some point during the stated timeframe, whilst we complete maintenance work.

The service outage should only last for up to 30 minutes, however a 1-hour timeframe has been given in the event of any unforeseen circumstances.

This is for planned work to replace key networking components at our UK datacenter.

This outage has been moved to Thursday 7th April 11:00 - 12:00 UTC to avoid a conflicting change request.

•  Scheduled for Thu, 7 Apr 2022 11:00 UTC •  Expected to take 1 hour Previous IncidentsPast noticesNo further notices from the past 7 days.

Need Support?

• support@globalgraphics.com Powered by Sorry™



All systems are go

Don't agree with this? Please let us know

• Application

• Connections

• Email Sync

• Services

• Tools

• Mailigen

Previous Incidents

[Resolved] Workflow automations issue

Began: 30 Mar 13:19 UTC  Ended: 30 Mar 14:36 UTC  Duration: 1 hour and 17 minutes

• Tools

 

• Workflow Automation

Wed, 30 Mar 202213:19:38 UTC

We've noticed some issues regarding Workflow automations. Our team is working to fix it as soon as possible. Don't worry, we'll update you as soon as the system is up and running again. Sorry for the inconvenience!

13:29:33 UTC

Issue was identified to be taking place for users in EU region only where workflow automations actions are delayed. We have implemented the fix and monitoring the effect at the moment.

We will provide further update once we see service state is back to normal. We apologize for any inconvenience caused.

14:36:40 UTC

You're all good! Seems like everything is working on our end. Still having issues? Clear your browser, cache, and cookies and try again. Contact us for further assistance.

[Resolved] Contacts Issue

Began: 24 Mar 13:30 UTC  Ended: 24 Mar 14:41 UTC  Duration: 1 hour and 10 minutes

• Tools

 

• Contacts

Thu, 24 Mar 202213:30:53 UTC

Hmmm. Something’s not quite right. We’re looking into a reported issue with Contacts. Sorry for the inconvenience, we will update you as soon as possible.

14:41:50 UTC

Everything should now be back to normal. If anything still seems not working properly, please clear your browser cache and cookies for pipedrive page and try again. If things still don’t seem right, contact us and we’ll investigate further.

[Resolved] Workflow automations issue

Began: 21 Mar 16:17 UTC  Ended: 21 Mar 16:54 UTC  Duration: 36 minutes

• Tools

 

• Workflow Automation

Mon, 21 Mar 202216:17:38 UTC

We've noticed some issues regarding Workflow automations. Our team is working to fix it as soon as possible. Don't worry, we'll update you as soon as the system is up and running again. Sorry for the inconvenience!

16:27:22 UTC

We identified the issue to be taking place for users in EU region only.

We already applied fix and monitoring recovery process then provide updates shortly.

We apologize for any inconvenience caused.

16:54:34 UTC

You're all good! Seems like everything is working on our end. Still having issues? Clear your browser, cache, and cookies and try again. Contact us for further assistance.

[Resolved] Webapp not loading

Began: 15 Mar 18:31 UTC  Ended: 15 Mar 19:57 UTC  Duration: 1 hour and 26 minutes

• Application

 

• Web App

Tue, 15 Mar 202218:31:18 UTC

Hi everyone,

We are receiving reports that some users are having issues loading Pipedrive. Our Engineering Teams are working on a fix at this very moment and as always we'll keep you updated of any developments.

We apologise for this disturbance.

19:20:09 UTC

Fix implemented. Everything should now be back to business as usual. But we are still doing some further checks. So clear your browser, cache, and cookies and try again, and if that doesn’t work contact us.

19:57:40 UTC

Phew. All is fixed! Everything should now be back to business as usual. Still in doubt? Clear your browser, cache, and cookies and try again. For anything else, contact us.

[Resolved] Email sync issue

Began: 7 Mar 20:18 UTC  Ended: 7 Mar 23:25 UTC  Duration: 3 hours and 6 minutes

• Email Sync

 

• Email Integration

 

• Smart BCC

Mon, 7 Mar 202220:18:55 UTC

We've noticed some issues regarding Email sync. Our team is working to fix it as soon as possible. Don't worry, we'll update you as soon as the system is up and running again. Sorry for the inconvenience!

23:25:11 UTC

Everything should now be back to normal. If anything still seems not working properly, please clear your browser cache and cookies for pipedrive page and try again. If things still don’t seem right, contact us and we’ll investigate further.

[Resolved] issues with Automations email actions in US

Began: 3 Mar 18:20 UTC  Ended: 3 Mar 19:32 UTC  Duration: 1 hour and 12 minutes

• Tools

 

• Workflow Automation

Thu, 3 Mar 202218:20:21 UTC

Hmmm. Something’s not quite right. We’re looking into a reported issue with Automations sending emails. Sorry for the inconvenience - we will update you as soon as possible.

19:32:52 UTC

Phew. All is fixed and well in the world! Everything should now be back to business as usual. Still in doubt? Clear your browser, cache, and cookies and try again. For anything else, contact us.

Past noticesNo further notices from the past 30 days.

Need Support?

• support@pipedrive.com

https://pipedrive.com/support Powered by Sorry™


Signature (functions)

A function signature (or type signature, or method signature) defines input and output of functions or methods.

A signature can include:

• parameters and their types

• a return value and type

• exceptions that might be thrown or passed back

• information about the availability of the method in an object-oriented program (such as the keywords public, static, or prototype).

In depth

Signatures in JavaScript

JavaScript is a loosely typed or a dynamic language. That means you don't have to declare the type of a variable ahead of time. The type will get determined automatically while the program is being processed. A signature in JavaScript can still give you some information about the method:

MyObject.prototype.myFunction(value) Copy to Clipboard

• The method is installed on an object called MyObject.

• The method is installed on the prototype of MyObject (thus it is an instance method) as opposed to being a static method.

• The name of the method is myFunction.

• The method accepts one parameter, which is called value and is not further defined.

Signatures in Java

In Java, signatures are used to identify methods and classes at the level of the virtual machine code. You have to declare types of variables in your code in order to be able to run the Java code. Java is strictly typed and will check any parameters at compilation time if they are correct.

public static void main(String[] args) Copy to Clipboard

• The public keyword is an access modifier and indicates that this method can be called by any object.

• The static keyword indicates that this method is a class method as opposed to being an instance method.

• The void keyword indicates that this method has no return value.

• The name of the method is main.

• The method accepts one parameter of type String Array. It is named args.

See also • Java internal type signatures on Wikipedia Found a problem with this page? • Edit on GitHub • Source on GitHub • Report a problem with this content on GitHub • Want to fix the problem yourself? See our Contribution guide. Last modified: Jan 21, 2022, by MDN contributorsj174.250.210.135 (talk)°→→→

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, while argument (sometimes called actual parameter) refers to the actual input supplied at function call. For example, if one defines a function as def f(x): ..., then x is the parameter, and if it is called by a = ...; f(a) then a is the argument. A parameter is an (unbound) variable, while the argument can be a 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, f(2) and a = 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 for pass-by-reference or 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 f(x) = x*x the variable x is a parameter; in the function call f(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 its parameter 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 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 subroutine is called at run-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 the parameter 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's common to pass in an argument of type void* and cast it to an expected type:

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.
}

To better understand the difference, consider the following function written in C:

int Sum(int addend1, int addend2)
{
  return addend1 + addend2;
}

The function Sum has two parameters, named addend1 and addend2. 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 the Sum function might look like this:

int value1 = 40;
int value2 = 2;
int sum_value = Sum(value1, value2);

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.

Alternative convention in Eiffel

Within the Eiffel software development method and language, the terms argument and parameter have distinct uses established by convention. The term argument is used exclusively in reference to a routine's inputs,[7] and the term parameter is used exclusively in type parameterization for generic classes.[8]

Consider the following routine definition:

    sum (addend1: INTEGER; addend2: INTEGER): INTEGER
        do
            Result := addend1 + addend2
        end

The routine sum takes two arguments addend1 and addend2, which are called the routine's formal arguments. A call to sum specifies actual arguments, as shown below with value1 and value2.

    sum_value: INTEGER
    value1: INTEGER = 40
    value2: INTEGER = 2
                
            sum_value := sum (value1, value2)

Parameters are also thought of as either formal or actual. Formal generic parameters are used in the definition of generic classes. In the example below, the class HASH_TABLE is declared as a generic class which has two formal generic parameters, G representing data of interest and K representing the hash key for the data:

class HASH_TABLE [G, K -> HASHABLE] 
            

When a class becomes a client to HASH_TABLE, the formal generic parameters are substituted with actual generic parameters in a generic derivation. In the following attribute declaration, my_dictionary is to be used as a character string based dictionary. As such, both data and key formal generic parameters are substituted with actual generic parameters of type STRING.

    my_dictionary: HASH_TABLE [STRING, STRING]

Datatypes

In strongly typed programming languages, each parameter's 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 subroutine has no parameters; in formal type theory, such functions take an empty parameter list (whose type is not void, but rather 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, C++, Clojure,[citation needed] Common Lisp,[9] Fortran 90,[10] Python, Ruby, Tcl, and Windows PowerShell[citation needed] allow for a default 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 as Optional) then the language provides a well-known value (such as null, Empty, zero, an empty string, etc.) if a value is not provided by the caller.

PowerShell example:

function doc($g = 1.21) {
    "$g gigawatts? $g gigawatts? Great Scott!"
}
PS  > doc
1.21 gigawatts? 1.21 gigawatts? Great Scott!

PS  > doc 88
88 gigawatts? 88 gigawatts? Great Scott!

Default arguments can be seen as a special case of the variable-length argument list.

Variable-length parameter lists

Some languages allow subroutines to be defined to accept a variable number of arguments. For such languages, the subroutines must iterate through the list of arguments.

PowerShell example:

function marty {
    $args | foreach { "back to the year $_" }
}
PS  > marty 1985
back to the year 1985

PS  > marty 2015 1985 1955
back to the year 2015
back to the year 1985
back to the year 1955

Named parameters

Some programming languages—such as Ada and Windows PowerShell—allow subroutines to have named parameters. 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:

function jennifer($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!

Multiple parameters in functional languages

In lambda 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 as currying. Some programming languages, like ML and Haskell, 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 actually syntactic sugar for the definition of a function that returns a function, etc. Function application is left-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.

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++,[b] while other languages have built-in support for output parameters. Languages with built-in support for output parameters include Ada[11] (see Ada subprograms), Fortran (since Fortran 90; see Fortran "intent"), various procedural extensions to SQL, such as PL/SQL (see PL/SQL functions)[12] and Transact-SQL, C#[13] and the .NET Framework,[14] Swift,[15] and the scripting language TScript (see TScript function declarations).

More precisely, one may distinguish three types of parameters or parameter modes: input parameters, output parameters, and input/output parameters; these are often denoted in, out, and in out or inout. 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 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 void 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(WString text, Font font : Integer width, Integer height)

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.[11] For instance, while in C# input parameters (default, no keyword) are passed by value, and output and input/output parameters (out and ref) are passed by reference, in PL/SQL input parameters (IN) are passed by reference, and output and input/output parameters (OUT and IN OUT) are by default passed by value and the result copied back, but can be passed by reference by using the NOCOPY compiler hint.[16]

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 and Fortran 66 and Fortran 77, as in this Pascal example:

function f(x, y: integer): integer;
begin
    f := x + y;
end;

This is semantically different in that when called, the function is simply evaluated – it is not passed a variable from the calling 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.

For example, to return two variables from a function in C, one may write:

int width
int height;

F(x, &width, &height);

where x is an input parameter and width and height 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 TryParse method in .NET, especially C#, which parses a string into an integer, returning true on success and false on failure. This has the following signature:[17]

public static bool TryParse(string s, out int result)

and may be used as follows:

int result;
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.

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.[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 prevent 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:

Object obj = G(y, F(x));

when written with output and input/output parameters instead becomes (for F it is an output parameter, for G an input/output parameter):

Object obj;
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:

Object obj;
G(y, F(x, &obj));

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 or Python, such as:

def f():
    return 1, 2
a, b = f()

For returning a value of one of several types, a tagged union can be used instead; the most common cases are nullable 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)
if result is None:
    # exception handling

or, more idiomatically:

try:
    result = parse(s)
except ParseError:
    # 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:

WidthHeight width_and_height = F(x);

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.[18]

See also

Notes

  1. ^ In this article, the term "subroutine" refers to any subroutine-like construct, which have different names and slightly different meanings depending on the programming language being discussed.
  2. ^ 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.

References

  1. ^ "Passing Information to a Method or a Constructor (The Java™ Tutorials > Learning the Java Language > Classes and Objects)". Oracle.com. Retrieved 2021-09-09. 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.
  2. ^ Prata, Stephen (2004). C primer plus (5th ed.). Sams. p. 276–277. ISBN 978-0-672-32696-7.
  3. ^ "Working Draft, Standard for Programming Language C++" (PDF). www.open-std.org. Retrieved 1 January 2018.[permanent dead link]
  4. ^ Gordon, Aaron. "Subprograms and Parameter Passing". rowdysites.msudenver.edu/~gordona. Archived from the original on 1 January 2018. Retrieved 1 January 2018.
  5. ^ Dollard, Kathleen. "Passing Arguments by Value and by Reference (Visual Basic)". docs.microsoft.com. Retrieved 2018-10-27.
  6. ^ "The GNU C Programming Tutorial". crasseux.com. Retrieved 2018-10-27.
  7. ^ Meyer, Bertrand. Object-Oriented Software Construction, 2nd Edition, Prentice Hall, 1997, p 444.
  8. ^ Meyer, p. 96.
  9. ^ "Functions". gigamonkeys.com. Retrieved 2021-06-02.
  10. ^ "optional arguments". www.netlib.org. Retrieved 2021-06-02.
  11. ^ a b 8.2 Parameter Modes, "Rationale for the Design of the Ada® Programming Language"
  12. ^ 8. PL/SQL Subprograms: Specifying Subprogram Parameter Modes
  13. ^ a b Peter Hallam. "Why does C# have both 'ref' and 'out'?". Archived from the original on 2011-09-26.
  14. ^ ParameterDirection Enumeration
  15. ^ Functions — The Swift Programming Language (Swift 4.2)
  16. ^ 8. PL/SQL Subprograms: Passing Large Data Structures with the NOCOPY Compiler Hint
  17. ^ Int32.TryParse Method (String, Int32)
  18. ^ a b CA1021: Avoid out parameters