Default Values of Arguments

Sometimes when we use a function in C++, we find that we code some of the arguments with the same values almost every time.

Example: We have a function Check which plays the game of checkers against a human opponent. The prototype statement looks like this:

     void Check(char);

and the code for Check looks like this:

     void Check(char First)
     {
     //lots of code
     }

Usually the human player moves first (First='H'), but occasionally the human player wants the computer to move first (First='C'). That is, most of the time we code

     Check('H');

but once in a while we have

     Check('C');

It would be convenient if we only had to code the value of the argument when it had the unusual value.

The C++ language allows us to do this. An argument of a function can have a default value. We would need to change the prototype statement:

     void Check(char = 'H');

The code would remain the same as before. We specify the default value the first time the rpogram's name occurs, which is in the prototype statement.

We could now call the function in at least two ways:

     Check();     // The default value of First will be used.
     Check('C');  // First will have the specified value 'C'.

Of course, functions can have more than one argument. Some arguments may have default values and some may not. It is required, though, that any arguments which do not have default values must come earlier on the list than any which do have default values.

For example, these prototype statements are illegal:

     int Funk1(char = 'A', int);
     float Funk2(float, int = 14, bool);
     char Funk3(int = 7, char = 'B', float);

but these are legal:

     int Funk4(int, char = 'A');
     bool Funk5(float, char = 'M', int = 42);
     char Funk6(char = 'K', int = 3, float = 2.718);

When we call a function with several arguments having default values, we can provide a non-default value for an argument, but we also have to provide values for all the arguments occurring earlier on the list.

Thus, for instance, these statements are legal:

     cout << Funk6('M', 5, 9.1);
     cout << Funk6('M');    // Default values 3 and 2.718 will be used.
     cout << Funk6('A', 7); // Default value 2.718 will be used.

but these statement would be illegal:

     cout << Funk6(9.1);
     cout << Funk6(5, 7.8); 
     cout << Funk6('J', 3.5);

In each case, the problem is that the compiler cannot manage to match the actual arguments accurately with the formal arguments.