Default Argument

In computer programming, a default argument is an argument 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).

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. For example, in the following function declaration:

int my_func(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:

result = my_func(1, 2, 3); result = my_func(1, 2);

In the first case the value for the argument called c is specified as normal. In the second one, 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 printToScreen(istream &input = cin) { // this outputs any input to the screen cout << input; }

The function call:

printToScreen;

will by default print input from the keyboard to the screen. As this is the most commonly used behaviour it makes sense not to specify

printToScreen(cin);

on the other hand any parameter of type istream can now be passed to the same function and the function will print to screen from the source specified as the parameter to the function. Consider:

printToScreen(fileName);

where fileName is a file that has been opened to read via ifstream's open function call.


Some other languages, like Java, do not have default arguments. However, the same behaviour can be simulated by using method overloading 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) { return MyFunc(a, b, 12); } int MyFunc(int a, int b, int c) { /* main implementation here */ }

Famous quotes containing the words default and/or argument:

    In default of inexhaustible happiness, eternal suffering would at least give us a destiny. But we do not even have that consolation, and our worst agonies come to an end one day.
    Albert Camus (1913–1960)

    Your views are now my own.
    Marvin Cohen, U.S. author and humorist.

    In conversation, after having taken a strong position in an argument and heard a complete refutation of his position.