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 anal ...
, 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 dialect ...
to a function 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++) 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 ...
!" to the standard output 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.