Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ functions

C++ functions

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 additional functions.

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

functionDeclarationtells the compiler the function's name, return type, and parameters. A functiondefineprovides 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.

Functions also have many other names, such as method, subroutine, or procedure, and so on.

Defining a function

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

return_type

function_name

(

parameter

list

)

{

body

of

the

function

}

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

Example

The following are max() The source code of the function. This function has two parameters num1 and num2 and returns the larger of the two numbers:

// Function returns the larger of 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

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 includes 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 parameter names are not important; only the parameter types are required, so 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, a function declaration is required. In this case, you should declare the function at the top of the file that calls it.

Calling a function

When creating a C++ function, you define what the function does, then complete the defined task by calling the function.

When the program calls a function, program control is transferred to the called function. The called function executes the defined task, and when the function's return statement is executed, or the closing brace of the function is reached, program control is returned to the main program.

When calling a function, pass the required arguments; if the function returns a value, you can store the return value. For example:

Example

#include

<
iostream
using
namespace
std

;

// Function declaration

int

max

(

int

num1

,

int

num2

)

;

int

main

(

)

{

// local variable declaration

int

a

=

100

;

int

b

=

200

;

int

ret

;

// Call function to get the maximum value

ret

=

max

(

a

,

b

)

;

cout

<<

"

Max value is :

"

<<

ret

<<

endl

;

return

0

;

}

// Function returns the larger of 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 running the final executable, the following result is produced:


Max value is : 200

Function parameters

If a function wants to use parameters, it must declare variables that accept the parameter values. These variables are called the function'sformal 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 function's formal parameter. In this case, modifying the formal parameter inside the function has no effect on the actual argument.
call by pointer This method assigns the argument's address to the formal parameter. Inside the function, that address is used to access the actual argument used in the call. This means modifying the formal parameter affects the actual argument.
call by reference This method assigns the argument's reference to the formal parameter. Inside the function, that reference is used to access the actual argument used in the call. This means modifying the formal parameter affects the actual argument.

By default, C++ uses thecall by valueto pass arguments. Generally, this means 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 for parameters

When you define a function, you can specify a default value for each parameter later in the parameter list. When the function is called, if the actual argument's value is left empty, 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, 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

)

;

}

int

main

(

)

{

// local variable declaration

int

a

=

100

;

int

b

=

200

;

int

result

;

// Call function to add values

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 code above is compiled and executed, it produces the following result:


Total value is :300
Total value is :120

Lambda Functions and Expressions

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

A Lambda expression treats a function as an object. Lambda expressions can be used like objects, for example assigned to variables and passed as arguments, and can also be evaluated like functions.

A Lambda expression is essentially very similar to a function declaration. 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 intermediate results. Like an ordinary function, the value of z is not preserved for the next time the unnamed function is called again.

If a lambda function has no return value (e.g., void), its return type can be completely omitted.

Inside a Lambda expression you can access variables of the current scope; this is the Lambda expression's closure behavior. Unlike JavaScript closures, C++ variable passing has the distinction between pass-by-value and pass-by-reference. You can specify it via the leading []:


[]      // 沒有定义任何变量。使用未定义变量会引发错误。
[x, &y] // x以传值方式传入(默认),y以引用方式传入。
[&]     // 任何被使用到的外部变量都隐式地以引用方式加以引用。
[=]     // 任何被使用到的外部变量都隐式地以传值方式加以引用。
[&, x]  // x显式地以传值方式加以引用。其余变量以引用方式加以引用。
[=, &z] // z显式地以引用方式加以引用。其余变量以传值方式加以引用。

Also note one thing. For the [=] or [&] forms, the lambda expression can directly use the this pointer. However, for the [] form, to use the this pointer you must explicitly pass it:


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