Week 1: Inline functions, function overloading, function default parameters

Inline function

  • Function calls have time overhead. When invoking a function, it takes a few instructions to put func on the stack and leave the stack after finishing. If the function has only a few sentences and the execution is fast, the function is called many times, and the overhead will be very large.
  • In order to reduce the function call overhead, the inline function mechanism is introduced. Processing calls to inline functions is to insert the entire code into the call statement without generating the call function statement.
  • disadvantage: Increased program volume

Definition: inline int max()add the keyword inline

Function overloading

  • The same name but different parameters are function overloading
  • Function overloading makes function naming easier
  • The compiler determines which function to use based on the number and type of actual parameters
void Max(double a,double b);
void Max(int a,int b);
void Max(double a,double b,double c);
int main()
{
	int a=10,b=11;
	double r1=5.2,r2=6.3,r3=9.1;
	Max(a,b);
	Max(r1,r2);
	Max(r1,r2,r3);
}

void Max(int a,int b)
{
	cout<<"invoking max 1...\n";
	if(a>b)
		cout<<"Max is "<<a<<endl;
	else
		cout<<"Max is "<<b<<endl; 
}

void Max(double a,double b)
{
		cout<<"invoking max 2...\n";
	if(a>b)
		cout<<"Max is "<<a<<endl;
	else
		cout<<"Max is "<<b<<endl;
}

void Max(double a,double b,double c)
{
		cout<<"invoking max 1...\n";
	if(a>b&&a>c)
		cout<<"Max is "<<a<<endl;
	else if(b>a&&b>c) 
		cout<<"Max is "<<b<<endl;
	else
		cout<<"Max is "<<c<<endl;
}

Output result:Insert picture description here

PS. The max function cannot be named here, because it conflicts with a function in the iostream library?

Function default parameters

When defining parameters, several consecutive parameters on the far right have default values

void func(int x1, int x2=2, int x3=3);
func(10); //equal to func(10,2,3)
func(10,8); // equal to func(10,8,3)
func(10,8,9); // equal to func(10,8,9)
func(10, ,9) ; //error 
  • The purpose of function default is to improve the scalability of the program
  • If a written function needs to add new parameters, and the original calling function may not use the new parameters, then you can avoid modifying those function call statements and use the new parameters.

Guess you like

Origin blog.csdn.net/ZmJ6666/article/details/108548431