Detailed resolution of the default parameters of functions in C++

  • 2020-04-02 01:51:08
  • OfStack

Usage:
(1) when the function is declared or defined, directly assign a value to the parameter, which is the default parameter.
(2) when a function is called, part or all of the parameters are omitted, and the default parameters are used instead.

Notes:
(1) generally, the default parameter is set in the declaration function.

If default parameters are set when the function is declared and when the function is defined, the default parameter declared by the function takes precedence.


#include<iostream>
using namespace std;
int main()
{
 double add(double a=3.2,double b=9.6);//Set default parameters when the function is declared
 cout<<add()<<endl;         //Using default parameters
 return 0;
}
double add(double a=3.2,double b=9.5)//Set default parameters when defining a function
{
 return a+b;
}

Operation results:
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201310/20130921225015703.png ">

(2) the definition order of default parameters is from right to left.

That is, if a default value is set, the parameter to the right should also be set to a default value.

That is:


<pre name="code" class="cpp">int add(int a,int b=1,int c=1);</pre>  

This is the right thing to do.

And:


int add(int a=1,int b,int c);

This is wrong.
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201310/20130921225750937.png ">
This is because when arguments are passed to the system, the system matches the parameters from left to right.

If I add(1,2), then a is equal to 1, b is equal to 2, and c is equal to what? We can't get the value of c until we've passed in all the arguments, but why set the default arguments to the function?

So the build system doesn't allow the programmer to do that, because it's pointless.
(3) the call order of default parameters is from left to right.

When we use functions, arguments must be written from left to right.



add(1,2,3);//Pass the value of three parameters
add(1,2);//Pass the value of two parameters
add(1);//Pass the value of a parameter
add();//The value of the parameter is not passed

add(,2,3);//You cannot omit the value of the parameter on the left. You should pass the value from right to left

Error:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201310/20130921231528453.png ">

Related articles: