Easy Tutorial
❮ Cpp Copy Constructor Cpp Strings ❯

C++ Function

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

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

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

The C++ Standard Library provides a large number of functions that can be called by your program. For example, the strcat() function is used to concatenate two strings, and the memcpy() function is used to copy memory to another location.

Functions have many names, such as methods, subroutines, or procedures, among others.

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. Here are all the parts of a function:

Example

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

// Function to return 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

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

The function declaration includes the following parts:

return_type function_name( parameter list );

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

int max(int num1, int num2);

In the function declaration, the names of the parameters are not important, only their 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 file, a function declaration is necessary. In this case, you should declare the function at the top of the file calling the function.

Calling a Function

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

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

When calling a function, you pass the required parameters, and 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 to return 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; 
}

Combining the max() function and the main() function, compile the source code. When running the final executable file, the following result will be produced:

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 known as the function's formal parameters.

Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

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

Call Type Description
Call by Value This method copies the actual value of an argument into the formal parameter of the function. Changes made to the parameter inside the function have no effect on the actual parameter.
Call by Pointer This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the actual argument.
Call by Reference This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the actual argument.

By default, C++ uses call by value to pass arguments. Generally, this means that code within a function cannot alter the arguments used to call the function. The earlier example, calling the max() function, used the same method.

Default Values for Parameters

When you define a function, you can specify a default value for each of the last parameters. If the value of the actual parameter is left empty when calling the function, the default value is used.

This is done by using the assignment operator to assign a value to the parameter in the function definition. When calling the function, if the parameter's value is not passed, the default value is used; if a value is specified, the default value is ignored, and the passed value is used. Consider 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;

   // Calling the function to add values
   result = sum(a, b);
   cout << "Total value is :" << result << endl;

   // Calling 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 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).

Lambda expressions treat the function as an object. They can be used like objects, such as being assigned to variables, passed as parameters, and 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. Like a regular function, the value of z does not persist to the next call of this unnamed function.

If the lambda function does not return a value (e.g., void), its return type can be completely omitted.

Within a Lambda expression, variables from the current scope can be accessed, which is the closure behavior of the Lambda expression. Unlike JavaScript closures, C++ has both pass-by-value and pass-by-reference for variable passing. This can be specified by the [] at the beginning:

[]      // No variables defined. Using undefined variables will cause an error.
[x, &y] // x is passed by value (default), y is passed by reference.
[&]     // Any external variables used are implicitly passed by reference.
[=]     // Any external variables used are implicitly passed by value.
[&, x]  // x is explicitly passed by value. Other variables are passed by reference.
[=, &z] // z is explicitly passed by reference. Other variables are passed by value.

It's also worth noting that for the [=] or [&] forms, the lambda expression can directly use the this pointer. However, for the [] form, if the this pointer needs to be used, it must be explicitly passed in:

[this]() { this->someFunc(); }();
❮ Cpp Copy Constructor Cpp Strings ❯