Default Parameter
   HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, a default argument is an
argument An argument is a statement or group of statements called premises intended to determine the degree of truth or acceptability of another statement called conclusion. Arguments can be studied from three main perspectives: the logical, the dialectic ...
to a
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the
C programming language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well as ...
). Later languages (for example, in
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
) allow the programmer to specify default arguments that always have a value, even if one is not specified when calling the function.


Default arguments in C++

Consider the following function declaration: int MyFunc(int a, int b, int c = 12); This function takes three arguments, of which the last one has a default of twelve. The programmer may call this function in two ways: int result = MyFunc(1, 2, 3); result = MyFunc(1, 2); In the first case the value for the argument called ''c'' is specified as normal. In the second case, the argument is omitted, and the default value of ''12'' will be used instead. There is no means to know if the argument has been specified by the caller or if the default value was used. The above-mentioned method is especially useful when one wants to set default criteria so that the function can be called with or without parameters. Consider the following: void PrintGreeting(std::ostream& stream = std::cout) The function call: PrintGreeting(); will by default print "
hello world ''Hello'' is a salutation or greeting in the English language. It is first attested in writing from 1826. Early uses ''Hello'', with that spelling, was used in publications in the U.S. as early as the 18 October 1826 edition of the ''Norwich C ...
!" to the
standard output In computer programming, standard streams are interconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin ...
std::cout (typically the screen). On the other hand, any object of type std::ostream can now be passed to the same function and the function will print to the given stream instead of to the standard output. PrintGreeting(std::cerr); Because default arguments' values are "filled in" at the call site rather than in the body of the function being called,
virtual function In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part o ...
s take their default argument values from the static type of the pointer or reference through which the call is made, rather than from the dynamic type of the object supplying the virtual function's body. struct Base ; struct Derived : public Base ; int main()


Overloaded methods

Some languages, such as
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
, do not have default arguments. However, the same behaviour can be simulated by using
method overloading In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that f ...
to create overloaded methods of the same name, which take different numbers of arguments; and the versions with fewer arguments simply call the versions with more arguments, with the default arguments as the missing arguments: int MyFunc(int a, int b) int MyFunc(int a, int b, int c) However, in addition t
several other disadvantages
since the default arguments are not modeled in the type system, the type of a callback (aka higher-order function) can't express that it accepts either of the overloads nor simulate the default arguments with overloaded functions. Whereas
in JavaScript
the non-overloaded function definition can substitute the default when the input value is undefined (regardless if it was implicitly undefined via the argument's absence at the call site or an explicitly passed undefined value); which is modeled as an optional argument parameter type ?:
JavaScript's solution i
not resolved statically
(i.e. not at compile-time, which is why TypeScript models only the optionality and not the default values in the function's type signature) thus incurs additional runtime overhead, although it does provide more flexibility in that callbacks can independently control their defaults instead of centrally dictated by the (callback's type signature in the) type signature of the function which inputs the callback. The TypeScript solution can b
simulated in Java
with the Optional type except the analogous of an implicit undefined for each absent argument is an explicit Optional.absent() at the call site.


Evaluation

For every function call default argument values must be passed to the called function. If a default argument value contains side-effects, it is significant when those side effects are evaluated – once for the entire program (at parse time, compile time, or load time), or once per function call, at call time. Python is a notable language that evaluates expressions in default arguments once, at the time the function declaration is evaluated. If evaluation per function call is desired, it can be replicated by having the default argument be a
sentinel value In computer programming, a sentinel value (also referred to as a flag value, trip value, rogue value, signal value, or dummy data) is a special value in the context of an algorithm which uses its presence as a condition of termination, typically in ...
, such as None, and then having the body of the function evaluate the default value's side effects only if the sentinel value was passed in. For example: import random def eager(a=random.random()): return a x = eager() y = eager() assert x

y def lazy(a=None): if a is None: a = random.random() return a x = lazy() y = lazy() assert x != y


Extent

Generally a default argument will behave identically to an argument passed by parameter or a local variable declared at the start of the function, and have the same
scope Scope or scopes may refer to: People with the surname * Jamie Scope (born 1986), English footballer * John T. Scopes (1900–1970), central figure in the Scopes Trial regarding the teaching of evolution Arts, media, and entertainment * Cinem ...
and extent (lifetime) as a parameter or other local variable, namely an
automatic variable __NOTOC__ In computer programming, an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or b ...
which is deallocated on function termination. In other cases a default argument may instead be statically allocated. If the variable is mutable, it will then retain its value across function calls, as with a
static variable In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
. This behavior is found in Python for mutable types, such as lists. As with evaluation, in order to ensure the same extent as a local variable, one can use a sentinel value: def eager(a=[]): return a x = eager() x += [1] assert eager()

[1] def lazy(a=None): if a is None: a = [] return a x = lazy() x += [1] assert lazy()

[]


References

{{reflist Articles with example C++ code Articles with example Python (programming language) code C++ Subroutines