C++ functions and function calls (pass by value, pointer, call by reference)

        A function is a group of statements that together perform a task. Every C++ program has at least one function, the main function main() , and all simple programs can define other additional functions.

        You can divide your code into different functions. It's up to you how to divide your code into different functions, but logically, the division is usually based on each function performing a specific task.

        A function declaration tells the compiler the name, return type, and parameters of a function. A function definition provides the actual body of the function.

        The C++ standard library provides a large number of built-in functions that programs can call. For example, the function strcat() is used to concatenate two strings, and the function memcpy() is used to copy memory to another location.

        There are many other names for functions, such as methods, subroutines, or programs, and so on.

define function

The general form of a function definition in C++ is as follows:

return_type function_name(parameterlist) { bodyofthefunction }

In C++, a function consists of a function header and a function body. The following lists all the components of a function:

  • Return Type: A function can return a value. return_type is the data type of the value returned by the function. Some functions perform the desired operation without returning a value, in this case return_type is the keyword void .
  • Function Name: This is the actual name of the function. The function name and parameter list together form the function signature.
  • Parameters: Parameters are like placeholders. When the function is called, you pass a value to the parameter, and this value is called the actual parameter. The parameter list includes the type, order, and number of function parameters. Parameters are optional, that is, the function may not contain parameters.
  • Function body: The function body contains a set of statements that define the tasks that the function performs.

example

Below is the source code of the max() function. The function takes two parameters num1 and num2 and returns the larger of the two numbers:

// The function returns the larger of the two numbers
int max(int num1, int num2)
{
 // local variable declaration
 int result;
 if (num1 > num2) result = num1;
 else result = num2;
 return result;
}

function declaration

A function declaration tells the compiler the name of the function and how to call the function. The actual body of the function can be defined separately.

A function declaration consists of the following parts:

return_type function_name( parameter list );

For the function max() defined above, the following is the function declaration:

int max(int num1,int num2); 

In a function declaration, the name of the parameter is not important, only the type of the parameter is required, so the following is also a valid declaration:

int max(int,int); 

A function declaration is required when you define a function in one source file and call the function in another. In this case, you should declare the function at the top of the file that calls the function.

Call functions

When you create a C++ function, you define what the function does, and then call the function to accomplish the defined task.

When a program calls a function, program control transfers to the called function. The called function performs a defined task, returning program control to the main program when the function's return statement is executed, or when the function's closing parenthesis is reached.

When calling a function, pass the required parameters, and if the function returns a value, you can store the return value. E.g:

example

#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
intmain()
{ // local variable declaration
	int a = 100; int b = 200; int ret;
	// call the function to get the maximum value
	ret = max(a, b);
	cout << "Max value is : " << ret << endl;
	return 0;
}
// The function returns the larger of the two numbers
int max(int num1, int num2)
{
	// local variable declaration
	int result;
	if (num1 > num2) result = num1;
	else result = num2;
	return result;
}
 
    

Put the max() function and the main() function together and compile the source code. When the final executable is run, the following results are produced:

Max value is:200  

function parameter

If the function is to take parameters, it must declare a variable that accepts the parameter's value. These variables are called formal parameters of the function .

Formal parameters, like other local variables within a function, are created when the function is entered and destroyed when the function is exited.

When calling a function, there are two ways to pass parameters to the function:

调用类型 描述
传值调用 该方法把参数的实际值复制给函数的形式参数。在这种情况下,修改函数内的形式参数对实际参数没有影响。
指针调用 该方法把参数的地址复制给形式参数。在函数内,该地址用于访问调用中要用到的实际参数。这意味着,修改形式参数会影响实际参数。
引用调用 该方法把参数的引用复制给形式参数。在函数内,该引用用于访问调用中要用到的实际参数。这意味着,修改形式参数会影响实际参数。

By default, C++ uses call-by-value to pass arguments. In general, this means that the code inside the function cannot change the parameters used to call the function. The previously mentioned instance, when calling the max() function, uses the same approach.

the default value of the parameter

When you define a function, you can specify default values ​​for each parameter that follows in the parameter list. When calling the function, if the value of the actual parameter is left blank, this default value is used.

This is done by using the assignment operator in the function definition to assign a value to the parameter. When calling the function, if no value is passed for the parameter, the default value is used, if a value is specified, the default value is ignored and the passed value is used. See the example below:

example

#include <iostream>
using namespace std;
int sum(int a, int b = 20)
{
	int result; result = a + b;
	return (result);
}
intmain()
{ // local variable declaration
	int a = 100; int b = 200; int result;
	// call function to add value
	result = sum(a, b);
	cout << "Total value is :" << result << endl;
	// call the function again
	result = sum(a);
	cout << "Total value is :" << result << endl;
	return 0;
}

When the above code is compiled and executed, it produces the following results:

Total value is:300Total value is:120 
 

Lambda functions and expressions

C++11 provides support for anonymous functions, called Lambda functions (also called Lambda expressions).

Lambda expressions treat functions as objects. Lambda expressions can be used like objects, i.e. they can be assigned to variables and passed as parameters, and they can be evaluated like functions.

Lambda expressions are very similar in nature to function declarations. The specific form of lambda expression is as follows:

[capture](parameters)->return-type{body}

E.g:

[](int x,int y){return x < y ;}   

If there is no return value can be expressed as:

[capture](parameters){body}

E.g:

[]{ ++ global_x ; }   

In a more complex example, the return type can be specified explicitly as follows:

[](int x,int y)->int{int z = x + y;return z + x;}       

In this example, a temporary parameter z is created to store intermediate results. As with normal functions, the value of z is not retained until the next time the unnamed function is called again.

If the lambda function does not return a value (eg void), its return type can be completely ignored.

Variables in the current scope can be accessed within a lambda expression, which is the Closure behavior of a lambda expression. Unlike JavaScript closures, C++ variable passing has the distinction between pass-by-value and pass-by-reference. It can be specified by preceding []:

[] // No variables are defined. Using an undefined variable throws an error. [ x , & y ] // x is passed by value (default), y is passed by reference. [&] // Any external variables that are used are implicitly referenced by reference. [=] // Any used external variables are implicitly referenced by value. [&, x ] // x is explicitly referenced by value. The remaining variables are referenced by reference. [=, & z ] // z is explicitly referenced by reference. The rest of the variables are referenced by value.      
  
     
     
  
  

Another thing to note. For the form [=] or [&], lambda expressions can use the this pointer directly. However, for the form of [], if you want to use the this pointer, you must explicitly pass it in:

[this](){this->someFunc();}();   

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325685569&siteId=291194637