The function can give the default parameter value in advance when declaring it, and if the argument is given, the actual parameter value is used, otherwise the default value is given beforehand.
int Add (int5,int6return x + y;} int Main () { Add (ten); 10+20 Add (ten); 10+6 Add (); 5 + 6 }
Description Order of default parameter values
A parameter with a default parameter must be at the end of the formal parameter list, that is, the right side of the default argument value cannot have an argument with no default value, because the combination of the actual participating parameters is left-to-right in order to be invoked.
int Add (int x, int y = 5 , int z = 6 ); // correct int Add (int x = 1 , int y = 5 , int z); // error int Add (int x = 1 , int y, int z = 6 ); // error
Default parameter values and function call locations
If a function has a prototype declaration, and the prototype declaration is preceded by the definition, the default parameter value must be given in the function prototype declaration, and if only the definition of the function, or the function is defined before, the default parameter value is given in the function definition
#include <iostream>using namespacestd;intAddintx =5,inty =6);intMain () {cout<<Add (); System ("Pause"); return 0;}intAddintXinty) { returnX +y;}
Result is 11
#include <iostream>usingnamespace std; int Add (int5int6) { return x + y;} int Main () { cout<<Add (); System ("pause"); return 0 ;}
Same result
Examples of functions with default parameter values:
Calculate the volume of a box: the sub-function Getvolume is a function that calculates the volume, has three parameters: Lengrh (Long), Width (width), height (height), where width and height have default values
The Getvoluime function is called in different form in the main function to analyze the running result of the program.
#include <iostream>#include<iomanip>using namespacestd;intGetvolume (intLengthintwidth =2,intHeight =3);intMain () {Const intX =Ten, Y = A, Z = the; cout<<"Some Box Data is"; cout<< getvolume (x, Y, z) <<Endl; cout<<"Some Box Data is"; cout<< Getvolume (X, Y) <<Endl; cout<<"Some Box Data is"; cout<< Getvolume (X) <<Endl; System ("Pause"); return 0;}intGetvolume (intLengthintWidthintheight) {cout<< SETW (5) << length << setw (5) << width << setw (5) << Height <<Endl; returnLength * Width *height;}
Output Result:
c++--function with default parameter values