Default Function Arguments

A C++ function prototype can list default values for some of the parameters. If you omit the corresponding arguments when you call the function, the compiler automatically uses the default values. If you provide your own arguments, the compiler uses them instead of the defaults. The following prototype illustrates this feature:

void myfunc( int i = 5, double d = 1.23 );

Here, the numbers 5 and 1.23 are the default values for the parameters. You could call the function in several ways:

myfunc( 12, 3.45 ); // Overrides both defaults

myfunc( 3 ); // Same as myfunc( 3, 1.23 )

myfunc(); // Same as myfunc( 5, 1.23 )

If you omit the first argument, you must omit all arguments that follow. You can omit the second argument, however, and override the default for the first. This rule applies to any number of arguments. You cannot omit an argument unless you omit all the arguments to its right. For example, the following function call is illegal:

myfunc( , 3.5 ); // Error: cannot omit only first argument

A syntax like this is error-prone and would make reading and writing function calls more difficult.

The following example uses default arguments in the show function.

// A program with default arguments in a function prototype

#include <iostream.h>

void show( int = 1, float = 2.3, long = 4 );

void main()

{

show(); // All three arguments default

show( 5 ); // Provide 1st argument

show( 6, 7.8 ); // Provide 1st and 2nd

show( 9, 10.11, 12L ); // Provide all three argument

}

void show( int first, float second, long third )

{

cout << "\nfirst = " << first;

cout << ", second = " << second;

cout << ", third = " << third;

}

When you run this example, it prints

first = 1, second = 2.3, third = 4

first = 5, second = 2.3, third = 4

first = 6, second = 7.8, third = 4

first = 9, second = 10.11, third = 12

Default values provide a lot of flexibility. For example, if you usually call a function using the same argument values, you can put them in the prototype and later call the function without supplying the arguments.