A default argument is a value that's used automatically if you omit the corresponding actual argument from a function call.
For example, if in my_func(int n) n has a default value of 1, the function call my_func() is the same as my_func(1).
To establish a default value, use the function prototype.
The compiler looks at the prototype to see how many arguments a function uses.
The following prototype creates a function with default parameter.
char * left(const char * str, int n = 1);
The function above returns a char pointer.
To leave the original string unaltered, the const qualifier for the first argument is used.
You want n to have a default value of 1, so you assign that value to n.
A default argument value is an initialization value.
If you leave n alone, it has the value 1, but if you pass an argument, the new value overwrites the 1.
When you use a function with an argument list, you must add defaults from right to left.
int my_func(int n, int m = 4, int j = 5); // VALID int my_func(int n, int m = 6, int j); // INVALID int my_func(int k = 1, int m = 2, int n = 3); // VALID
// Using default arguments.
#include <iostream>
using namespace std;
/*www.ja va 2 s. com*/
// function prototype that specifies default arguments
int boxVolume( int length = 1, int width = 1, int height = 1 );
int main()
{
// no arguments--use default values for all dimensions
cout << "The default box volume is: " << boxVolume();
// specify length; default width and height
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 1 and height 1 is: " << boxVolume( 10 );
// specify length and width; default height
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height 1 is: " << boxVolume( 10, 5 );
// specify all arguments
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height 2 is: " << boxVolume( 10, 5, 2 )
<< endl;
} // end main
// function boxVolume calculates the volume of a box
int boxVolume( int length, int width, int height )
{
return length * width * height;
}
The code above generates the following result.
The following code creates a string function with a default argument.
#include <iostream>
using namespace std;
const int SIZE = 80;
char * left(const char * str, int n = 1);
/*from www .j a v a 2 s.c om*/
int main(){
char sample[SIZE];
cout << "Enter a string:\n";
cin.get(sample,SIZE);
char *ps = left(sample, 4);
cout << ps << endl;
delete [] ps; // free old string
ps = left(sample);
cout << ps << endl;
delete [] ps; // free new string
return 0;
}
char * left(const char * str, int n){
if(n < 0)
n = 0;
char * p = new char[n+1];
int i;
for (i = 0; i < n && str[i]; i++)
p[i] = str[i]; // copy characters
while (i <= n)
p[i++] = '\0'; // set rest of string to '\0'
return p;
}
The code above generates the following result.