C + + function definition and call

Posted by sysop on Sun, 23 Jan 2022 23:29:34 +0100

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

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

Function declarations tell the compiler the name, return type, and parameters of a function. The 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 connect 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.

1. Define function

The general form of 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. All components of a function are listed below:

  • 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 required 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 the parameter list together form the function signature.
  • Parameters: parameters are like placeholders. When the function is called, you pass a value to the parameter, which is called the actual parameter. The parameter list includes the type, order and quantity of function parameters. Parameters are optional, that is, functions may not contain parameters.
  • Function body: the function body contains a set of statements that define the execution task of the function.

example

The following is the source code of the max() function. This function has two parameters num1 and num2, which will return the larger of the two numbers:

// 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; }

2. Function declaration

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

The 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 the function declaration, the name of the parameter is not important. Only the type of the parameter is required. Therefore, the following is also a valid declaration:

int max(int, int);

When you define functions in a source file and call functions in another file, function declarations are required. In this case, you should declare the function at the top of the file that calls the function.

3. Call function

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

When a program calls a function, program control is transferred to the called function. The called function executes the defined task. When the return statement of the function is executed or the end bracket of the function is reached, the program control will be returned to the main program.

When calling a function, pass the required parameters. If the function returns a value, you can store the return value. For example:

example

#include <iostream> 
using namespace std; 
int max(int num1, int num2);//Function declaration
int main ()//Local variable declaration 
{
 int a = 100; 
 int b = 200; 
 int ret; 
 ret = max(a, b); //Call the function to get the maximum value
 cout
<< "Max value is : " << ret << endl;
 return 0; } int max(int num1, int num2) { // Local variable declaration  int result;  if (num1 > num2)   result = num1;  else  result = num2;  return result; }
//Output result:
Max value is : 200

4. Function parameters

If a function wants to use parameters, it must declare variables that accept parameter values. These variables are called formal parameters of the function.

Formal parameters, like other local variables in a function, are created when entering the function and destroyed when exiting the function.

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

Call typedescribe
Value passing call This method assigns the actual value of the parameter to the formal parameter of the function. In this case, modifying the formal parameters in the function has no effect on the actual parameters.
Pointer call This method assigns the address of the parameter to the formal parameter. In the function, this address is used to access the actual parameters to be used in the call. This means that modifying the formal parameters will affect the actual parameters.
Reference call This method assigns the reference of the parameter to the formal parameter. Within the function, the reference is used to access the actual parameters to be used in the call. This means that modifying the formal parameters will affect the actual parameters.

By default, C + + uses value passing calls to pass parameters. In general, this means that the code in the function cannot change the parameters used to call the function. The example mentioned earlier uses the same method when calling the max() function.

Default values for parameters

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

This is done by using assignment operators in the function definition to assign values to parameters. When calling a function, if the value of the parameter is not passed, the default value will be used. If a value is specified, the default value will be ignored and the passed value will be used. See the following example:

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; result = sum(a, b);// Call a function to add a value cout << "Total value is :" << result << endl; result = sum(a);// Call the function again cout << "Total value is :" << result << endl; return 0; } //When the above code is compiled and executed, it will produce the following results: Total value is :300 Total value is :120

5.Lambda functions and expressions

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

Lambda expressions treat functions as objects. Lambda expressions can be used like objects, such as assigning them to variables and passing them as parameters, and evaluating them like functions.

Lambda expressions are essentially very similar to function declarations. The specific form of 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 case, a temporary parameter z is created to store intermediate results. Like a normal function, the value of z will not be retained until the next time the unnamed function is called again.

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

Variables in the current scope can be accessed within the Lambda expression, which is the Closure behavior of the Lambda expression. Unlike JavaScript closures, C + + variable passing is different from passing values and references. You can specify through the preceding []:

[]      // No variables defined. Using undefined variables raises an error.
[x, &y] // x Passed in by value (default), y Passed in by reference.
[&]     // Any external variable used is implicitly referenced.
[=]     // Any external variable used is implicitly referenced by value.
[&, x]  // x Explicitly referenced by value. Other variables are referenced by reference.
[=, &z] // z Explicitly referenced by reference. Other variables are referenced by value passing.

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

[this]() { this->someFunc(); }();
Original link: C + + functions | rookie tutorial (runoob.com)

Topics: C++