C++ Function
Functions are a set of statements that together perform a task. Every C++ program has at least one function, the main functionmain(), and all the simplest programs can define additional functions.
You can divide your code into different functions. How to divide code into different functions is up to you, but logically, division is usually based on each function performing a specific task.
FunctionDeclarationTells the compiler the function's name, return type, and parameters. FunctiondefinitionProvides 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 functionstrcat()A function used to concatenate two strings.memcpy()Used to copy memory to another location.
Functions also have many other names, such as methods, subroutines, or procedures, and so on.
Define Function
The general form of a function definition in C++ is as follows:
In C++, a function consists of a function header and a function body. Below is a list of all the components of a function:
- Return type:A function can return a value.return_typeIs the data type of the value returned by the function. Some functions perform the required operations without returning a value; in this case, return_type is the keywordvoid。
- Function name:This is the actual name of the function. The function name and the parameter list together constitute the function signature.
- Parameters:Parameters are like placeholders. When a function is called, you pass a value to the parameter; this value is called an actual argument. The parameter list includes the types, order, and number of the function's parameters. Parameters are optional, that is, a function may contain no parameters.
- Function body:The function body contains a set of statements that define the task the function performs.
Example
The following aremax()The source code of the function. This function has two parameters, num1 and num2, and returns the larger of the two numbers:
Function Declaration
FunctionDeclarationTells the compiler the function name 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 function declaration is as follows:
int max(int num1, int num2);
In a function declaration, the names of the parameters are not important; only the types of the parameters are required. Therefore, the following is also a valid declaration:
int max(int, int);
When you define a function in one source file and call it in another file, a function declaration is required. In this case, you should declare the function at the top of the file that calls the function.
Call Function
When creating 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 is transferred to the called function. The called function executes the defined task. When the function's return statement is executed, or when the closing brace of the function is reached, program control is returned to the calling program.
When calling a function, pass the required arguments. If the function returns a value, you can store the return value. For example:
Example
Put the max() function and the main() function together, and compile the source code. When the final executable file is run, it produces the following results:
Max value is : 200
Function parameters
If a function is to use parameters, it must declare variables that accept the values of the parameters. These variables are called the function's formal parameters.Formal parameters。
Formal parameters are like other local variables inside the function; they are created when entering the function and destroyed when exiting it.
When calling a function, there are three ways to pass arguments to the function:
| Call Type | Description |
|---|---|
| Call by value | This method assigns the actual value of the argument to the formal parameter of the function. In this case, modifying the formal parameter inside the function has no effect on the actual argument. |
| Call by Pointer | This method assigns the address of the argument to the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that modifying the formal parameter affects the actual argument. |
| Call by Reference | This method assigns a reference to the argument to the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that modifying the formal parameter affects the actual argument. |
By default, C++ usesCall by valueto pass parameters. In general, this means that the code inside the function cannot change the arguments used to call the function. In the example mentioned earlier, the same method was used when calling the max() function.
Default values of parameters
When you define a function, you can specify a default value for each of the parameters that follow in the parameter list. When calling the function, if the actual argument is left blank, this default value is used.
This is done by using the assignment operator in the function definition to assign values to the parameters. When the function is called, if no value is passed for a parameter, the default value is used; if a value is specified, the default value is ignored and the passed value is used. See the following example:
Example
When the above code is compiled and executed, it produces the following results:
Total value is :300 Total 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, for example, they can be assigned to variables and passed as arguments, and they can also be evaluated like functions.
Lambda expressions are essentially very similar to function declarations. The specific form of a Lambda expression is as follows:
[capture](parameters)->return-type{body}
For example:
[](int x, int y){ return x < y ; }
If there is no return value, it can be expressed as:
[capture](parameters){body}
For example:
[]{ ++global_x; }
In a more complex example, the return type can be explicitly specified 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 the intermediate result. As with an ordinary function, the value of z is not retained until the next time this unnamed function is called.
If a lambda function does not return a value (for example, void), its return type can be completely omitted.
Variables in the current scope can be accessed inside a Lambda expression; this is the closure behavior of Lambda expressions. Unlike JavaScript closures, C++ variable passing distinguishes between pass-by-value and pass-by-reference. This can be specified through the preceding []:
[] // 沒有定义任何变量。使用未定义变量会引发错误。 [x, &y] // x以传值方式传入(默认),y以引用方式传入。 [&] // 任何被使用到的外部变量都隐式地以引用方式加以引用。 [=] // 任何被使用到的外部变量都隐式地以传值方式加以引用。 [&, x] // x显式地以传值方式加以引用。其余变量以引用方式加以引用。 [=, &z] // z显式地以引用方式加以引用。其余变量以传值方式加以引用。
One more thing to note. For the forms [=] or [&], the lambda expression can directly use the this pointer. However, for the [] form, if you want to use the this pointer, it must be passed explicitly:
[this]() { this->someFunc(); }();
other extensions