In C++, it is allowed to give a default value to the formal parameter in the formal parameter list of a custom function. In this way, if there are actual parameters when calling, then the method of passing the actual parameters to the formal parameters will be used; if there are no actual parameters when calling, If you specify the corresponding actual parameter, the formal parameter will use the default value.
For example, a function that performs addition has the following code:
#include<iostream>usingnamespacestd;intadd(inta=3,intb=5){returna+b;}intmain(){cout<<add(10,20)<<endl;//Give 10 and 20 to a and 20 respectively bcout<<add(30)<<endl;//Give 30 to a, b is the default 5cout<<add()<<endl;//Use the default values 3 and 5 of a and b return0;}
Everyone read the code and experimented on the computer. The results are as follows:
It should be noted that since the order of passing parameters is pushed onto the stack from right to left, parameters with default values must be placed on the rightmost side of the formal parameter list! In addition, when a function needs to be declared in advance, if there are default parameters for the formal parameters, the default value can be specified in the declaration part, but the default value will no longer be specified in the subsequent function definition part.
Please do more experiments on the computer based on the actual situation!