Banner Image

C++

Diving Deeper: Understanding Functions and Arrays in C++

Written by Rahul Lath

Updated on: 17 Aug 2023

tutor Pic

In this article we delve into an essential component in c++: Functions. Functions are an essential part of C++ programming. 

They allow you to break down your code into smaller, more manageable pieces that can be reused throughout your program. In C++ functions are blocks of code that perform a specific task. 

You can think of them as mini-programs within your main program. Functions can take input, perform operations on that input, and return output.

There are several types of C++ functions, including void functions, value-returning functions, and reference-returning functions.

  • Void functions do not return a value and are used when you need to perform a task without returning a result. 
  • Value-returning functions return a value of a specific data type, such as an integer or a string.
  • Reference-returning functions return a reference to a variable, which allows you to modify the original variable’s value.

Let’s take a look at an example of C++ functions. Suppose you want to write a program that calculates the area of a circle. You could write a function that takes the radius of the circle as input, performs the necessary calculations, and returns the area of the circle. This function would be a value-returning function, as it returns a value (the area of the circle) of type float or double.

In summary, C++ functions are an essential tool for organizing and reusing code. They come in several types, including void functions, value-returning functions, and reference-returning functions. By writing functions, you can make your code more modular and easier to understand.

Syntax

  • return_type is the type of value that the function returns. 
  • function_name is the name of the function
  • parameters are the input values that the function takes
  • code block inside the function is executed when the function is called
  • return statement specifies the value that the function returns.

Here’s an example of a function that takes two integers as input and returns their sum:

In this example, the function is named “sum”, and it takes two integers ‘a’ and ‘b’ as input, you can use any variable name . The function then adds the variables and returns the result.

Why do we need functions?

In C++ functions are vital for many reasons.

  • They allow us to modularize code and make it easier to read and understand. 
  • They also allow us to reuse code, which  saves time and reduces errors. 
  • They make the code more efficient by breaking it down into smaller, more manageable parts.

Types of functions

There are two types of function in c++ types: standard library functions and user-defined functions. Standard library functions are built-in functions that are provided by the C++ standard library, such as “printf” and “sqrt”. User-defined functions are functions that are created by the programmer.

C++ Function Declaration

C++ function declaration is a way to tell the compiler that a function of this name exists. This is done by specifying the function name, return type, and parameter types. Here’s the syntax of a function declaration:

  • return_type is the data type of the value that the function returns
  • function_name is the name of the function
  • parameter_list is the list of input parameters the function takes.

Here is the function in c++ example declaration:

In this example, the sum function is declared with a return type of int and two integer parameters a and b

Calling a Function

Once a function is declared, you can call it from anywhere in the program.

Syntax of calling in C++ functions:

  • function_name is the name of the function
  • argument_list is the list of values passed to the function as input parameters.

 Calling a function in c++ example :

In this example, the sum function is called with two integer arguments, and the returned value is assigned to the variable result.

Parameter Passing to Functions

In C++ functions, there are two ways to pass arguments to a function:

  • call by value
  • call by reference.

In call by value, the value of the argument is passed to the function. Any changes made to the argument inside the function do not affect the original value of the argument.

 Call by value function in c++ example

In call by reference, the memory address of the argument is passed to the function. Changes made to the argument inside the function affect the original value of the argument.

Call by reference function in c++ example:

Functions using Pointers

Functions using pointers in C++ are a powerful tool for passing variables by reference to a function. A pointer is a variable that stores the memory address of another variable. Pointers can be used to manipulate variables indirectly and can be used to pass a variable by reference to a function.

Pointers in function in c++ example:

In this example, the swap function takes two integer pointers as input parameters. The function body swaps the values of the two variables pointed to by the pointers. The main function calls the swap function by passing the addresses of the variables a and b using the & operator.

Points to remember about functions in C++

  •  C++ functions can have multiple parameters of different data types.
  •  C++ functions can have a return type of void, which means it does not return any value.
  •  C++ functions can have a default argument, which is used when no argument is provided.
  •  C++ functions can be overloaded, which means multiple functions can have the same name but different parameter lists.
  •  C++ functions can be declared as static or extern, which affects its scope and linkage.
  •  C++ functions can call itself recursively, which is called recursion.

(Function Overloading,Storage classes and Recursion  will be covered in the later section)

C++ Function Overloading

C++ function overloading allows multiple functions with the same name but different parameter lists to coexist in the same program. A confusion that arises while programming this is that if the return type has to be the same, the answer to which is- No, it is not necessary for the functions with the same name to have same return type. This is useful when you want to perform the same operation on different data types(int, float,string etc)

In this example, there are two sum functions with the same name but different parameter lists. The first sum function takes two integer parameters and returns their sum, while the second sum function takes two float parameters and returns their sum.

C++ Default Argument

C++ default arguments are used to provide a default value for a function parameter if no argument is provided when the function is called.

In this example, the power function takes two integer parameters, x and y. The y parameter has a default value of 2. If no value is provided for y when the power function is called, it will use the default value of 2.

Static variable function in c++ example:

In this example, the counter function uses a static variable, count, which is initialized to 0. The count variable is incremented each time the counter function is called, and the value of count is printed to the console.

C++ recursion is a technique in which a function calls itself. Recursion is used to solve problems that can be broken down into smaller subproblems.

In this example, the factorial function is defined recursively. The function takes an integer parameter, n, and returns the factorial ofn. The base case for the recursion is when n is 0, in which case the function returns 1. Otherwise, the function multiplies n by the result of calling factorial with n-1.

C++ passing arrays to a function allows a function to operate on an array without needing to know the array’s size or contents.


In this example, the printArray function takes an integer array and its size as input parameters. The function loops through the array and prints each element to the console. The main function defines an integer array and its size, and then calls the printArray function with the array and its size.

The return statement in C++ is used to return a value from a function. The return type of a function must match the data type of the value being returned.


In this example, the add function takes two integer parameters and returns their sum using the return statement. The main function calls the add function and assigns the returned value to the variable result, which is then printed to the console.

C++ Storage Class

In C++ programming, a storage class is used to specify the scope and lifetime of a variable. There are four types of storage classes in C++: 

  • Auto
  • Register,
  • Static
  • extern.
  • auto storage class::It is used by default in C++ programming. Variables declared with the auto storage class are local to the block in which they are declared, and their lifetime is the block they are declared in.
  • register storage class:: It is used to define local variables that should be stored in a register instead of memory. This can result in faster access to the variable.
  • static storage class:: It is used to define variables that retain their values between function calls. Static variables have a lifetime that extends beyond the block in which they are declared.
  • extern storage class:: It is used to declare variables that are defined in another file. Extern variables are global in scope, and their lifetime is the entire program.

The output is:

C++ Recursion

Recursion is a technique in which a function calls itself. It can be useful for solving problems that can be broken down into smaller, similar sub-problems. Recursive functions have a base case to help in terminating the function so it doesnt run into an infinite loop and give a run time error.

Output is:

C++ Passing Array to Function

In C++ programming, arrays are passed to functions by reference. This means that any changes made to the array inside the function will affect the original array outside the function.

(Remember call by reference we discussed before)

Output is:

In this example, the printTheArray function takes an array arr and its size as the arguments of the function and prints the elements.

Return Statement

The return statement in C++ programming is used to return a value from a function. It can be used anywhere in the code to terminate the function after necessary condition is matched or necessary value is obtained. Functions can return any data type. C++ functions can only return one value, but that value can be anything like a complex structure (struct) or range from int to string.

Output is:

In this example, the add function takes two integers a and b as arguments and returns their sum. The main function calls add with the values of x and y and assigns the result to sum.

FAQS

What are the Benefits of Using User-Defined Functions in C++?

There are several benefits of using user-defined C++ functions. Some of them are:
Reusability: Functions can be reused in the program, reducing the amount of code.
Modularity: Functions can be used to break down a large program into smaller, more manageable parts.
Simplification:Functions help in simplifying complex tasks.
Improved readability: They can improve the readability of the code by encapsulating complex logic into a single function easily

Does C++ have a type function?

C++ does not have a built-in type function. Nevertheless, the typeid operator is often  used to determine the type of a variable at runtime. Here’s an example:

#include <iostream>
#include <typeinfo>
using namespace std;
int main() {
   int x = 5;
   double y = 3.14;
   cout << "Type of x is " << typeid(x).name() << endl;
   cout << "Type of y is " << typeid(y).name() << endl;
   return 0;
}

Output is:

Type of x is i
Type of y is d

Can a C++ function return more than one value?

A C++ function can only return one value, but that value can be anything like a complex structure (struct) or range from int to string. 

Can a C++ function call itself?

Yes, a C++ function can call itself and this is called recursion where a complex task can be recursively solved by breaking into smaller tasks.

References

  • 1. The C++ Programming Language (4th Edition) By Bjarne Stroustrup: https://www.stroustrup.com/4th.html
  • C++ Pocket Reference 1st Edition Accelerated C++: https://www.oreilly.com/library/view/c-pocket-reference/9780596801762/

Written by by

Rahul Lath

Reviewed by by

Arpit Rankwar

Share article on

tutor Pic
tutor Pic