Home Resource Centre C++ Function | A Comprehensive Guide (With Code Examples)

C++ Function | A Comprehensive Guide (With Code Examples)

Functions in C++ programming or any other programming language are building blocks that help in the organization and repetition of code with ease. Think of them like boxes that enclose a block of code that can be opened/ called upon whenever needed. They take parameters as input, run operations, and return results.

In this article, we will learn all about C++ functions, including how to create/ declare and define functions, their components, and how to use/ call them in C++ programs to get desired results. We will also discuss various types of functions in C++ with examples and detailed explanations.

How To Declare A Function In C++?

Function declaration refers to the act of creating a function, which may then be called upon from other parts of the program. C++ function declaration consists of the name of the function, its parameters (list of parameters) with applicable data types, and the data type of the function's return value.

In the structure of a C++ program, a function is usually declared at the beginning after header file inclusions. But we can also define a function inside the main() function. The function declaration differs from its definition (which we will discuss in the next section) as it includes the code body. Given below is the syntax followed when declaring a C++ function, followed by a detailed explanation of the same.

Syntax For Declaration Of C++ Function:

return_type function_name(parameter_type parameter_name) {
}
#include <iostream>

In the syntax above, we have declared a function before the inclusion of the header file <iostream>. This can also be done after we have included the necessary header file when writing the code. Here is an explanation of the C++ function syntax:

  1. Function Name (function_name): This term refers to the name of the function you are defining. It is best to pick a name that is both descriptive and accurate to the job it does. The name must adhere to C++'s naming guidelines.
  2. Return Type (return_type): It refers to the data type/ kind of value, if any, that the function will return. This can be int, float, char, etc. We can use the void keyword if the function doesn't return a value.
  3. Parameters (parameter_type parameter_name): These terms refer to the data type of parameter the function will take as input and the parameter's name. If there are numerous parameters, the names and data types are separated by commas.
  4. Curly Braces {}: The brackets contain the function's actual body (code), which describes its behaviour in reference to the parameters. This is a part of the function definition.

Examples of C++ Function Declaration:

Below are a few examples of function declarations in C++ language. Note that these will not generate any output since we need the complete function definition to implement them in a code. If you simply declare a function and call it without giving its definition, the program will throw an error.

// C++ function that takes two integer variables as parameters
// Function name is sum and the return type is int
int sum(int, int);

//C++ function that takes an integer pointer and an integer as parameters
//Function name is func and its return type is an integer pointer
int* func(int*, int);

Now let's discuss what we mean by C++ function definition and how we can use it in a C++ program to perform operations/ manipulations on data.

How To Define A C++ Function?

The function definition refers to the declaration of the function with the regular function body or function code. That is, the segment of code that we want to be implemented whenever the respective C++ function is called in the program.

The function definition can be done along with the declaration or separately. If done separately, we can define the C++ function either before or after the main() function. The syntax for a C++ function definition is similar to the declaration but with a code body added to it.

Syntax for C++ Function Definition:

return_type function_name(parameter_type parameter_name) {
// Code body that will be executed every time the function is called
//return statement
}

Here are the steps you must follow to define a function in C++:

  • Determine the function's goal: Choose the action or collection of instructions the function will take. In other words, this refers to the lines of code that define how the function will behave with the arguments passed to it.
  • Give the function a name: Choose a name that accurately describes the function's goal.
  • Choose the return type: Choose whether or not the function will return a value. If it does, be sure to define the return value's data type. Use "void" as the return type if the function returns nothing.
  • Identify the parameters: Check to see whether the function requires any parameters, often known as input values. Every argument has a name and a data type. If there are many parameters, provide their names and data types, separating them with commas.
  • Input the function body: Write the code that specifies the function's behaviour, i.e., what task after function call must be fulfilled. This code will be run every time the function is called.

Now that we know about the C++ function declaration and definition let's look at an example that shows how to define and call a function.

Code Example:

Output:

The product of 5 and 3 is: 15

Explanation:

In the C++ code example, we begin by including the essential header file <iostrem> for input-output operations. 

  1. We then declare a function multiply() with two integer parameters, num1 and num2, and an int return type. Note that at this point, we have not defined what the function does.
  2. Then, in the main() function, we declare and initialize two integer variables, a and b, with values 5 and 3, respectively.
  3. Next, we call the multiply() function by passing a and b as arguments, and the outcome of the function is stored in the variable result.
  4. Following this, we use the cout command to display the values of the numbers inside a string and the outcome of the function operation. 
  5. The main() function then terminates with a return 0 statement.
  6. As mentioned in the code comments, we provide the function definition detailing what the function must do with the parameters. 
  7. The function uses the multiplication arithmetic operator to calculate the product of the two numbers, stores it in the variable result and returns the same.
  8. In action, when the function is called in the main() function, this definition is executed, and the product of num1 and num2 is computed inside the multiply function.

The multiply function in this illustration delivers the product of two integer arguments. The values of a and b are sent as parameters to the function call multiply(a, b), and the result is produced as output. A function's parameters and arguments are detrimental to its successful implementation. In the sections ahead, we will discuss these concepts in detail, with the help of examples.

C++ Function Parameters

Variables specified within brackets of a function declaration or definition are called parameters. When a C++ function is called, these parameters serve as placeholders for the values that will be supplied to it.

  • A function's input requirements are specified by its parameters, which also enable the function to accept and work with different values each time it is called.
  • If there are numerous parameters, the names and data types are separated by commas.
  • The parameter's expected value type is indicated by the data type, which can be an int, float, char, etc.
  • A technique to transmit values from the calling code (arguments) to the function is also done with the help of these parameters.

Default Parameters & C++ Function

You may define default values for function parameters by using default parameters.

  • When a function is called without a matching parameter, the default setting is applied.
  • The function declaration/ prototype, and not the function definition, contains the default arguments.
  • Only the parameters at the very end of the parameter list can utilize default parameters.

Code Example:

Output:

Hello, Alice!
Hi, Bob!

Explanation:

  1. The program defines a welcome method/ function called greet.
  2. We have a default argument for the greeting parameter in the method, and it is set to Hello.
  3. We make two calls to the greet function in the main function, each time with a different set of inputs.
  4. We just supply the name parameter Alice in the initial call, and the greeting argument Hello is utilized by default. the result of this is Hello, Alice!, which is printed using std::cout.
  5. We override the default parameter in the second call by including the name Bob and greeting Hi arguments. Therefore, Hi, Bob! is the output.

Const Parameters In C++ Function

Const is the keyword used to indicate constant values. So, the const parameters refer to situations where a parameter's value cannot be changed inside the function.

  • Using const arguments for values that the function shouldn't alter is a smart idea.
  • Const arguments guarantee that the function won't unintentionally change the value of the argument that was supplied to it.

Code Example:

Output:

Value: 5

Explanation:

  1. We begin by defining a function called printValue, which takes a constant integer number as a parameter.
  2. Using std::cout, the printValue method will show the value supplied as an argument.
  3. As seen by the comment line // num = 10, the num argument is specified as const. Therefore, any attempt to change its value within the function would cause a compilation error.
  4. Value: 5 will be the only line of output.

C++ Function Arguments

When a function is called, arguments are the actual values supplied to the function. They line up with the function's arguments.

  • The values given as arguments are allocated to the respective function parameters when a function is invoked.
  • To guarantee effective data processing, the arguments must be in the same order, type, and quantity as the function's parameters.
  • Literals (constant values), variables, or expressions that evaluate the anticipated data type can all be used as arguments.

It's crucial to remember that for the C++ function to perform properly, the number, kind, and type of parameters and arguments must all match. If these aspects differ, then the program will throw a compilation error. Additionally, the types and order matter for matching the parameters. The parameter names in the function declaration or definition are not required.

Default Arguments In C++ Function

If no matching argument is given when the C++ function is called, the default value for the parameter can be specified using default arguments.

  • The C++ function declaration specifies the default parameters.
  • Only the parameters at the end of the parameter list may utilize default arguments.
  • With the use of this functionality, you may make some arguments optional while maintaining a default response in the absence of an argument.

Code Example:

Output:

Hello, Aarti!
Hi, Mehul!

Explanation:

  1. We begin by including necessary header files and then define the function greet.
  2. Name, a constant reference to a std::string, is the first parameter in the function. The default value for the second option, greeting, is Hello.
  3. In the primary role, the sole argument passed to the initial greet function call is the name Aarti.
  4. The default value of Hello is applied when a second parameter is not given. Hello, Aarti! is printed as a result.
  5. In the main function, the Mehul name parameter and the Hi greeting argument are both sent by the second call to the welcome function.
  6. It outputs the string message- Hi, Mehul! since the given argument Hi overrides the default value.
  7. Following that, the program returns 0, signifying a successful run.

Trailing Return Types

The ability to define a function's return type after the argument list is referred to as trailing return types.

  • This feature is especially helpful when the return type depends on the function's parameter types or requires intricate type expressions.
  • The auto keyword and the arrow operator (->) are used to identify trailing return types.

Code Example:

Output:

Result: 7

Explanation:

  1. In this code, the function add takes two int parameters, a and b, and returns their sum as an int.
  2. The auto keyword in the function definition is used along with the trailing return type -> int to specify the return type of the function.
  3. When the main function is executed, it calls the add function with arguments 3 and 4, and the result of the addition (3 + 4) is stored in the variable result.
  4. Then, it prints the value of the result using std::cout.

Return Statement In C++ Function

If a C++ function has a return type, then the return statement is used to end its execution and return a value.

  • We can employ the return statement anywhere in the function body.
  • The value that the function will return is indicated by the expression that comes after the return keyword.
  • The function execution ends immediately when the return statement is met.

Return Values In C++ Function

The values a C++ function returns to the calling program after it has finished execution are known as return values.

  • The return statement must be used when a function's return type is something other than void.
  • The returned value must be the same as the function's defined return type.
  • You can do further calculations on the return value, assign it to a variable, or use it as an argument when calling another function.

Code Example:

Output:

Result: 12

Explanation:

  1. The multiply function, defined in the example above, returns the product of the two integer inputs, a and b.
  2. The multiply function is used in the main function with inputs 3 and 4, and the result variable is set to the value that was returned.
  3. The std::cout command outputs Result: and the value of the result.
  4. In this instance, multiplying 3 by 4 yields the number 12, which is then reported as the output.

Types Of Functions In C++ With Examples

Depending on their application and purpose, there can be many types of C++ functions. The most commonly used basis for categorizing a function type is its origins. That is, if a C++ function comes from the standard library, it is referred to as a built-in function. Alternatively, if a C++ function is defined by the user to meet their specific needs, it is referred to as a user-defined or custom function. We have discussed both these in the section ahead.

C++ Standard Library Functions (In-built C++ Functions)

There are a number of built-in functions included in the standard library of C++. These functions are present in the corresponding header files and offer a variety of functionality. For example, the header file cmath contains many functions that help carry out mathematical operations/ manipulations on data. The C++ example below showcases how to use the sqrt() function, which calculates the square root of a given number. 

Code Example:

Output:

The square root of 16 is: 4

Explanation:

To utilize the sqrt() function, we add the required header file cmath in the code sample.

  1. In the next step, we make a variable declaration for the double-type variable number and assign it the value of 16.0.
  2. We declare another double variable, squareRoot, which calls the sqrt() function with the parameter number. The output is stored in this variable.
  3. Finally, we output the result together with a detailed message using std::cout.
  4. The result indicates that 16.0's square root is 4.0.

It's crucial to keep in mind that the sqrt() function is just one illustration of a built-in function in C++. Many additional functions, including those for managing files, text manipulation, and arithmetic computations, are available in the standard library.

User-Defined Functions In C++

A user-defined function refers to a function that users create/ define on their own to meet the needs of the program. In doing so, the user must specify the name, parameters, and return type in C++. This function can then be invoked from any section of the program to carry out a certain job.

In the example given below, we showcase how a user-defined function addNumbers is created. This function will accept two numbers as input and return their sum value.

Code Example:

Output:

The sum is: 8

Explanation:

  1. The user-defined function addNumbers is initially declared in the code sample with the return type integer (int) to indicate that it will return a value of integer data type.
  2. The function takes two input arguments, num1 and num2, which will be added inside the function.
  3. We compute the sum of num1 and num2 within the function and store the result in another variable called sum. The computed total is finally returned using the return statement.
  4. In the main() function, we then use parameters 5 and 3 to invoke the addNumbers method.
  5. The result is then saved in the result variable when the function completes the addition.
  6. The value of the result is then shown along with the informative message "The sum is:" using std::cout.

User-defined functions in C++ provide several benefits that contribute to code optimization, organization, reusability, and maintainability. The biggest advantage here is that they allow programmers to define any function to meet a specific goal. These functions can also be shared amongst programs and projects, like in-built C++ functions, if a repository of the same is created.

Type Of C++ Functions Based On Return Value

As mentioned, the return value refers to the value that a function returns after processing the lines of code contained in the curly brackets. In this section, we will discuss two more types of functions in C++ with examples based on their return value.

Void Function In C++ (Function With No Return Value)

A C++ function that doesn't return a value is known as a void function. They can execute a sequence of statements or carry out a specified operation without having to deliver a result. Void functions are frequently used for tasks like output display, changing global variables, or carrying out a sequence of instructions. Let's look at an illustration of the void C++ function for better understanding.

Code Example:

Output:

This is a void function.

Explanation:

  1. In the code sample above, we define a void function named displayMessage().
  2. There are no parameters required for this function, and its return type is void.
  3. We print the phrase "This is a void function." to the console from within the function using std::cout.
  4. We invoke the displayMessage() method in the main() function to run its code. The message is, therefore, shown on the console.

C++ Functions With Return Values

When you wish to carry out a certain activity and produce a value as a result of that operation, you utilize functions with return values. These functions may utilize fundamental data types (int, float, etc.), user-defined types, or even pointers as their data types. The image below illustrates the concept of return values in C++ functions.

Let's take a look at an example to gain a better understanding of a C++ function that does have a return value.

Code Example:

Output:

The sum is: 11

Explanation:

  1. We first define a function addNumbers(), which has the parameters a and b as two integers.
  2. The function uses the addition operator to calculate the sum of a and b and store it in the variable sum.
  3. The computed total is finally returned using the return statement.
  4. In the main() function, we call the addNumbers() function by passing integer values 8 and 5 as arguments.
  5. The result variable is then used to hold the returning value (sum).
  6. The value of the result is finally displayed using std::cout

Local Variable In C++ Function

The term function local variable refers to a variable that is declared inside a function and, hence, can only used inside the respective C++ function. That is,

  • Variables declared inside a C++ function are referred to as function local variables.
  • They are exclusive to the function and cannot be accessed from elsewhere.
  • When a C++ function is called, local variables are generated and then removed after the function is complete.
  • A fresh set of local variables is produced each time the function is called, and they only exist while that particular function call is being executed.

Accessibility and Exposure of Local Variable in a C++ Function:

  • Only the body of the C++ function, including any nested blocks or statements inside the function, has access to its local variables.
  • These variables are not accessible to or modifiable by other functions or codes outside of the function.
  • Due to their separation and distinct scopes, local variables can share the same name as variables in other functions or the global scope without triggering conflicts.

Lifetime of Local Variables Created in a C++ Function:

  • A local variable's lifespan starts when the function is invoked and ends when the function has finished running.
  • The memory for the local variables is released when the function is finished running.
  • The local variables cannot be utilized or accessed again after the function has finished and returned.

Code Example:

Output:

Local variable: 10

Explanation:

  1. In the above example, we define a function called exampleFunction, with variable localVar of type integer (int).
  2. Only the exampleFunction has access to this variable outside of that.
  3. It is used in the std::cout command after being initialized with the value 10.
  4. The value of localVar is printed, and any relevant procedures are carried out when exampleFunction is called from the main function.
  5. The localVar variable is deleted after the exampleFunction has finished running, making it impossible to retrieve it from outside the function.

Note: It's crucial to remember that every call to exampleFunction will have a unique instance of the localVar variable, independent from other calls to the function. A compilation error would occur if the localVar variable was altered or accessed from outside the function or after it had finished running.

Methods To Call A C++ Function

There are two primary ways to call the C++ function inside a program with access. In this section, we will discuss two methods, i.e., the call-by-value and call-by-reference ways for calling functions.

C++ Function | Call-By-Value

The call-by-value technique allows the arguments to be sent to a C++ function by making a duplicate of the values and giving them to the function. Since the function in this approach operates on copies of the original data, any changes performed inside the function do not impact the original values.

Code Example:

Output:

Before function call: 5
After function call: 5

Explanation:

  • We define a function increment() in the code above, which takes an integer parameter named num.
  • The local variable num is a replica of the value variable from the main function within the function.
  • The function increases the value of num, but it does not change the original value of the variable given in the main function.
  • As a result, the output is unaltered, and the value after the function call still has a value of 5.

C++ Function | Call-By-Reference

The call-by-reference way of passing arguments to a C++ function is when the function is called by supplying the memory location (reference) of the variables to be utilized inside the function. Since the variables in the function relate to the same memory address in this technique, any changes made to them also impact the original variables.

Code Example:

Output:

Before function call: 5
After function call: 6

Explanation:

  1. The function increment uses the reference or ampersand symbol (&) in the code above to take an integer parameter named num by reference.
  2. The variable num is a reference to the value variable from the main function inside the function.
  3. Since they both refer to the same memory address, the function actually changes the original value variable in the main function when it increases the value of num.
  4. As a result, the output demonstrates that after the function call, the value was increased by one to six.

Difference Between Call By Value & Call By Reference In C++ Function

The table given below contrasts the call-by-reference method against the call-by-value method of calling a C++ function.

Call by Value

Call by Reference

Copies the values of arguments.

Passes the memory address (reference) of arguments.

Modifying parameters inside the function does not affect the original variables.

Modifying parameters inside the function affects the original variables.

Memory for local variables is allocated and deallocated within the function.

No additional memory allocation or deallocation.

Requires more memory for storing copies of arguments.

It requires less memory as it directly operates on original variables.

Suitable for small-sized variables and situations where original values should not be modified.

Suitable for large-sized variables and situations where modification of original values is desired.

Arguments are evaluated and copied before passing to the function.

No evaluation or copying of arguments; only memory address is passed.

It can have a performance impact on large or complex data types.

Provides better performance for large or complex data types.

Syntax:

void functionName(Type parameter)

Syntax:

void functionName(Type& parameter)

Example:

void increment(int num) {
num++;}
int main() {
int value = 5;
increment(value);
// value is unchanged
return 0;}

Example:

void increment(int& num) {
num++;}
int main() {
int value = 5;
increment(value);
// value is modified to 6
return 0;}

How To Pass Parameters To Functions In C++?

There are three approaches to sending an argument to a C++ function in C++ which we have discussed in this section, with the help of examples.

Pass-by-Value Approach For C++ Function

When we are passing parameters to a function using the pass-by-value approach, a copy of the argument is provided to the function. The clone of the argument is used by the function, and any changes performed there have no impact on the original argument.

Note that the function's declaration argument is of the value type.

Code Example:

Output:

Before function call: 7
After function call: 7

Explanation:

  1. In the example above, we define a function called increment, which requires the integer (int) type argument num by value.
  2. The variable num is a duplicate of the value variable from the main function inside the function.
  3. The function increases the value of num, but it does not change the original value of the variable from the main function.
  4. The result demonstrates that after calling the function, the value's value is unaffected.

Pass-by-Reference Approach For C++ Function

Under the pass-by-reference, a reference to the argument is supplied to the C++ function. The original parameter can be directly accessed and changed by the C++ function. Note that the ampersand (&) is used in function declarations to denote a reference before an argument.

Code Example:

Output:

Before function call: 8
After function call: 9

Explanation:

  1. The reference/ ampersand symbol, &, is used to pass an int parameter named num by reference to the increment function.
  2. The variable num is a reference to the value variable from the main function inside the function.
  3. The function changes the original value variable in the main function by increasing the value of num.
  4. The result demonstrates that after the function call, the value's value was increased.

Pass-by-Pointer Approach For C++ Function

When using the pass-by-pointer approach, the C++ function is given the argument's memory location (or pointer). The C++ function has access to and control over the value through the pointer.

  • An asterisk (*) to denote a pointer is placed before the argument in the function definition.
  • The address of a legitimate variable or nullptr must be used as the parameter supplied to the function.

Code Example:

Output:

Before function call: 5
After function call: 6

Explanation:

  1. The pointer to an integer is passed as numPtr, an int* argument, to the increment function.
  2. The dereference operator (*) is used inside the function to increase the value referenced to, by numPtr.
  3. An integer variable named value is defined in the main function, and its address is given to the pointer ptr.
  4. The increment function receives the ptr, which enables it to indirectly change the value of value.
  5. The result demonstrates that after the function call, the value's value was increased.

How Does The Method To Pass Parameters To C++ Function Inpact The Complexity?

The underlying activities being carried out within the function are the key elements determining complexity. Hence, the complexity for parameter passing techniques (pass-by-value, pass-by-reference, and pass-by-pointer) does not change. The mechanism used to pass parameters has no effect on the function's temporal or spatial complexity.

In conclusion, pass-by-value makes a copy of the argument. The pass-by-reference approach gives users access to the original argument directly. Also, note that this method accesses and modifies the parameter in an indirect manner using a reference. The program's needs, such as whether the original value should be changed or the need to efficiently transfer big data structures, will determine which of these approaches should be used.

Why Do We Need Functions?

Functions are essential to programming because they offer benefits like code organization, reusability, and abstraction. We require C++ functions for the following main reasons:

  1. Modularity: C++ functions help segment difficult/ complex problems into more manageable bits. We may concentrate on fixing individual components by encapsulating certain functionality into functions. Because each function completes a particular goal, the code is simpler to comprehend, maintain, and debug. It encourages the organization of the code and lessens complexity.
  2. Code Reusability: The use of C++ functions facilitates code since, once defined, a function can be used repeatedly without the need to write the code again and again from scratch. This way, a C++ function encourages the DRY (Don't Repeat Yourself) philosophy, saves time and effort and minimizes code duplication.
  3. Abstraction: A C++ function offers a level of abstraction that lets you hide the specifics of operations. In other words, they help build a clear interface by obscuring implementation specifics. Implementation of abstraction also promotes effective code development and improves the readability and simplicity of code.
  4. Testing and Debugging: Since each C++ function completes a particular task, it is simpler to isolate and verify each function's accuracy. This makes the tasks of debugging and testing modules much easier. 
  5. Code Organization: A C++ function provides you with the ability to classify similar tasks/ processes into blocks, thus facilitating the logical organization of code. This also makes it simpler to search the code for a particular piece of functionality.
  6. Maintainability: With C++ functions, it's simpler to make updates or adjustments to a particular functionality. As long as the function's interface stays the same, you can improve or modify it without affecting other sections of the code. This enhances the codebase's maintainability.
  7. Readability: Using C++ functions allows us to segment the code making it more legible and self-explanatory. This greatly improves code readability while also simplifying maintained tasks.
  8. Encapsulation: C++ functions allow encapsulation of related processes and data within a defined scope. This helps minimize potential name conflicts and improve code robustness. For example, declaring local variables inside a C++ function restricts their visibility and accessibility to just that function.
  9. Performance Optimisation: A C++ function helps improve code performance by identifying and enhancing crucial code parts. That is, you can concentrate on optimizing particular sections without affecting the rest of the program by identifying bottlenecks and isolating them into distinct functions.
  10. Code Interoperability: Another benefit of using C++ functions is that they can be shared among many projects and programs. You can develop a library of reusable code that is simple to include in future projects by establishing libraries of functions. This speeds up development and encourages collaboration.

How Is A C++ Function Called In Recursion?

The recursive process refers to a situation where a function repeatedly calls itself until a set of pre-defined conditions are met. The basic idea behind recursion is to divide a bigger/ complex issue into smaller issues/ subproblems and then solve them to reach a solution. It is possible to tackle issues with repeated or self-similar structures using this type of function in C++ programs.

Syntax:

return_type function_name(parameters) {
// Base case - condition to terminate recursion
if (base_case_condition) {
// Return base case result
return base_case_result;
}
/* Recursive case - calls the function itself with modified arguments and combines the results to solve the problem*/
// Recursive call(s)
return combine_results(function_name(modified_parameters));
}

Code Example:

Output:

The factorial of 5 is: 120

Code Explanation:

The factorial function, which computes the factorial of a given number, is defined in the code above. The recursion operates as follows:

  1. The argument for the factorial function is an unsigned integer, n.
  2. Since the factorial of 0 and 1 equals 1, we return 1 in the base case if n is 0 or 1.
  3. In the recursive example, we call factorial again with the parameter n-1 before multiplying the outcome by n.
  4. The factorial problem is divided into smaller subproblems in this stage until the base case is reached.
  5. The results are pooled to determine the factorial of the initial number after the recursive calls are repeated until the base case is reached.
  6. We call factorial with a value of 5 in the main function and put the output in the result variable. The computed factorial is then printed to the console using std::cout.
  7. The factorial of 5, in this case, is calculated as 5 * 4 * 3 * 2 * 1, giving 120.

How To Pass An Array To Function In C++?

In C++, one may be required to deal with arrays inside of functions and perform manipulations or access the elements of the array. There are two ways to get this done when supplying an array to a C++ function, i.e., via reference or as a pointer. The syntax for both ways is given below, followed by an example.

The syntax for passing an array as a pointer:

void functionName(DataType* arrayName, int arraySize);

The syntax for passing an array by reference:

void functionName(DataType (&arrayName)[arraySize]);

Here,

  • The fucntionName refers to the name given to the function being defined.
  • Data type indicates the type of elements in the array.
  • The arraySize reflects the number of elements in the array.

Now, let's take a look at an example that showcases the implementation of these methods.

Code Example:

Output:

Before modification: 1 2 3 4 5
After modification: 2 4 6 8 10

Code Explanation:

  1. We define a function called modifyArray, which takes an integer array and its size as inputs.
  2. Inside the function, we use a for loop to iterate over each element of the array and then multiply the element by 2.
  3. Another function, modifyArrayRef is defined with a for loop to iterate over the elements and multiply them by 3.
  4. Then, in the main() function, an array of size 5 called arr is declared and initialized with the values 1, 2, 3, and 4.
  5. The std::cout is used to print the array before modification.
  6. When calling modifyArray, arr is sent as a pointer along with the array size. The loop within modifyArray iterates over the array's items and multiplies each one by two.
  7. As commented out in this example, the modifyArrayRef method, which gets the array by reference, can be used in place of modifyArray.
  8. Lastly, the main function outputs the array's elements after the modification has been made to the items in the array, once again using std::cout.

Note: You can see from the output that the array members have been changed in accordance with the function's logic.

  • The changes done inside the function affect the original array items, whether you give the array as a pointer or via reference.
  • To enable correct iteration and access within the method, it's vital to supply the array size together with the array when passing an array as a pointer.
  • As an alternative, the array size is automatically calculated when sending an array by reference based on the reference type.

Function Overloading In C++

The process of declaring multiple C++ functions with the same name but different components is referred to as function overloading. In other words, this technique calls for the coexistence of many functions with the same name but varied arguments or argument types.

Function overloading allows you to create functions that carry out equivalent actions on several data types or in different argument configurations. This enhances the readability, reuse, and flexibility of the code.

Syntax for C++ Function Overloading:

return_type function_name(parameter_list_1) {
// Function implementation
}
return_type function_name(parameter_list_2) {
// Function implementation
}
// Additional overloaded functions with different parameter lists

Here,

  • The function_name is the name of the function.
  • The parameter_list_1 and parameter_list_2 refer to the list of parameters taken by the function.
  • And return_type denotes the type of data/ value that the function will return.

Code Example:

Output:

Sum of two integers: 15
Sum of three integers: 12
Concatenated string: Hello, world!

Code Explanation:

  1. We have defined three sum functions that are overloaded in the lines of code provided above.
  2. The first sum function accepts two integer inputs and outputs their sum.
  3. The second sum function returns the sum of the three integer inputs it is given.
  4. The concatenated string is returned by the third sum function, which requires two string arguments.
  5. In the main function, we call each of the overloaded sum functions with separate parameters.
  6. Sum(5, 10) is the first overloaded function that is called. It returns the sum of 5 and 10, which is 15.
  7. The second overloaded function is called using the second function call, sum(2, 4, 6), which returns the sum of 2, 4, and 6, which is 12.
  8. The third overloaded function is called sum("Hello, ", "world!"), which concatenates the two strings to produce "Hello, world!".
  9. The capability of function overloading is demonstrated by printing the outcomes using std::cout statements.

It is evident from the example above that the overloading of C++ functions is done by defining numerous functions with the same name but distinct argument lists. When the C++ function is called, the right function is involved depending on the supplied inputs. Enabling the same function name to carry out several operations depending on the input offers flexibility and makes the code reusable.

Also Read: Function Overloading In C++ With Code Examples & Explanation

C++ Function | Important Points To Remember 

Function Declaration: A regular function declaration informs the compiler of the function's name, return type, and type of any optional parameters. Commonly, it comes before the main() method.

Function Prototype: A function's name, return type, and parameters are all listed in its declaration, which is known as a function prototype or function signature. Prior to the function's actual definition appearing in the code, it is used to alert the compiler about the function. Function header files are frequently used to store prototypes.

Function Definition: The definition of function outlines how the function will be used in practice. It contains the name, parameters, return type, and collection of statements that will be carried out when the function is called.

Calling a Function: To use a function, you must call it by enclosing its name in brackets. You pass the values or variables as arguments inside the brackets if the function supports parameters.

Return Type: A function's return type describes the kind of value that will be given back to the caller. A function's return type is specified as void if it has no output at all.

Functions may have a single argument or several parameters, which serve as placeholders for values provided to the function during callbacks. The function declaration and definition include a parenthetical declaration of the parameters.

Arguments: When you call a function, you supply real values or variables. These arguments can be used inside the body of the function after being supplied to it.

Default Arguments: C++ allows you to specify default values for any or all of the parameters of the function. When a function is called without an actual argument, the default value is applied.

Function Overloading: The C++ language supports the use of several functions with the same name but various parameter lists. The number, type, and order of the arguments all play a role in the compiler's decision over which function to call.

Recursion: In C++, functions have the ability to be recursive, which means they can call one another. These are specifically helpful when tackling issues that can be broken down into smaller subproblems.

Function Templates: Function templates are a feature of C++ that lets you construct generic functions that can work with many data types. Using templates makes it possible to create reusable code.

It is important to note that C++, by default, sends function arguments by value, which implies a copy of the value is created and provided to the function. The function can alter the original value supplied if you pass parameters by reference instead.

Conclusion

Functions in C++ are the building blocks of efficient and organized code. They encapsulate tasks, promote reusability, and enhance readability. With different types of functions and the ability to use default parameters and function overloading, C++ functions empower developers to create tailored solutions. By following best practices, like keeping functions concise and documenting them well, programmers can harness the true power of C++ functions to craft elegant and scalable applications.

Frequently Asked Questions

Q. Can we call the main function inside the main function in C++?

In C++, calling the main function from within another main function is feasible. However, one is not advised to do so, as it can result in irrational behaviour or infinite recursion. Recursive calls to the main function result in the creation of a fresh instance of the function on top of the original. This may lead to a loop in which each main function is continually called, leading the program to run endlessly.

Here is an illustration of how to call the main function repeatedly:

#include <iostream>

int main() {

std::cout << "Inside the first main function" << std::endl;
main(); // Recursive call to main function

return 0;
}

When you execute this program, it will keep printing "Inside the first main function" until the recursion limit is reached or a stack overflow problem occurs. Recursively invoking the main function( special function) is permitted by the C++ programming language standard. However, it is widely considered a bad programming practice. Recursively invoking the main function, which is intended to be the program's entry point, might make the code challenging to comprehend and maintain.

It is preferable to split repetitive activities into their own function and call that function from the main or any other suitable location in your program if you must execute those actions frequently.

Q. What are the 5 special member functions in C++?

The five special functions in C++ are constructor, default constructor, copy constructor, copy assignment operator, and move constructor and move assignment operator. They have been described below, with examples.

Default constructor: Whenever an object is created without any formal parameters, the default constructor is immediately invoked. The data members of the object are initialized with their default values. The compiler creates a default constructor if a class doesn't explicitly declare one.

class MyClass {
public:
MyClass() {
// Default constructor
}};

Copy constructor: When an existing object is copied into a new object, the copy constructor is invoked. It produces a brand-new object with identical values to the original. The compiler creates a copy constructor automatically if a class doesn't declare one.

class MyClass {
public:
MyClass(const MyClass& other) {
// Copy constructor
}};

Destructor: When an object exits its scope or is specifically destroyed, the destructor is immediately executed. It is in charge of relinquishing any dynamically allocated memory or resources that the object has accumulated. The compiler produces a default destructor if a class doesn't declare one.

class MyClass {
public:
~MyClass() {
// Destructor
}};

Copy Assignment Operator: This is used to transfer the values of one object to another already-existing object. It enables the assignment of objects of the same class type to one another. The compiler creates a copy assignment operator automatically if a class doesn't declare one.

class MyClass {
public:
MyClass& operator=(const MyClass& other) {
// Copy assignment operator
return *this;}
};

Move Constructor and Move Assignment Operator: With the introduction of the move constructor and move assignment operator in C++11, it is now possible to easily transfer resource ownership from one object to another.

  • They are called whenever an object is moved, often using move semantics or if an object is returned by value from a function.
  • A move constructor and move assignment operator are automatically generated by the compiler if a class doesn't declare them.

class MyClass {
public:
MyClass(MyClass&& other) {
// Move constructor
}
MyClass& operator=(MyClass&& other) {
// Move assignment operator
return *this;}
};

These five special member functions are automatically produced by the compiler if they are not explicitly declared and serve particular purposes. In order to ensure efficient handling of resources and appropriate function object behaviour, it is crucial to understand their behaviour and customize them as needed.

Q. What are the terms functions and structure in C++?

In C++, functions and structures are fundamental building blocks used to create programs. Let's take a closer look at functions and structures in C++:

C++ Functions C++ Structures
  • Functions in C++ are blocks of code that perform a specific task or action.
  • They are declared with a return type, a name, and an optional list of actual parameters.
  • Functions can be defined (implemented) to provide the actual code for the task they perform.
  • They can be declared and defined outside of the main() function and used in other parts of the program.
  • Functions are invoked (called) using their name and arguments (if any) enclosed in parentheses.
  • Functions can have a return type, which indicates the type of value they will return after completing their task. If a function does not return any value, the return type should be void.
  • Function parameters are variables that are passed to the function during the function call. Parameters allow the function to work with specific values.
  • C++ supports function overloading, allowing multiple functions with the same name but different type of parameter lists to coexist.
  • Recursion is also supported in C++ functions. Meaning functions can call themselves directly or indirectly to solve problems by breaking them down into smaller subproblems.
  • Structures in C++ are user-defined data types that allow you to group together different variables with different data types under a single name.
  • Each variable inside a structure is called a "member" or "field."
  • Structures are declared using the struct keyword followed by the name of the structure and a set of curly braces containing the member variables.
  • After defining a structure, you can create variables of that structure type.
  • Members of a structure are accessed using the dot . operator.
  • Structures are used to represent real-world entities with multiple related attributes. They provide a way to create custom data types tailored to specific needs.

Q. What are the 4 types of functions in C++?

The types of functions in C++ can be classified on the basis of their return value and arguments. They are described as follows (with examples):

Function without a return value or arguments: These functions take no arguments and don't yield any results. They are often employed to carry out a certain action or run a section of code. For example:

void showMessage() {
std::cout << "Hello, World!" << std::endl;}

Function with only the return value as an argument: These functions accept one or more parameters but do not return any value. They are utilized when a function needs input to complete a job. For example:

void printSum(int num1, int num2) {
int sum = num1 + num2;
std::cout << "Sum: " << sum << std::endl;}

Function that takes arguments but doesn't return anything: These functions do not take any parameters, just return a value. They are employed in the computation of results using internal logic. For example:

int getRandomNumber() {
return rand();}

Function with a return value and arguments: These functions receive one or more formal parameters and return a value. They are employed to calculate results depending on inputs. For example:

int calculateSum(int num1, int num2) {
return num1 + num2;}

These are the four primary types of C++ functions based on the method of passing arguments and the function's return type.

Here are a few other interesting C++ topics you must explore:

  1. C++ Type Conversion & Type Casting Demystified (With Examples)
  2. C++ If-Else | All Conditional Statements Explained With Examples
  3. OOPs Concept In C++ | A Detailed Guide With Codes & Explanations
  4. Dynamic Memory Allocation In C++ Explained In Detail (With Examples)
  5. Friend Function In C++ | Class, Types, Uses & More (+Examples)
Shivani Goyal
Manager, Content

I am an economics graduate using my qualifications and life skills to observe & absorb what life has to offer. A strong believer in 'Don't die before you are dead' philosophy, at Unstop I am producing content that resonates and enables you to be #Unstoppable. When I don't have to be presentable for the job, I'd be elbow deep in paint/ pencil residue, immersed in a good read or socializing in the flesh.

TAGS
Engineering Computer Science
Updated On: 2 May'24, 01:43 PM IST