Tutorial Study Image

Functions in C++

August 31, 2022, Learn eTutorial

In this tutorial, you will learn everything about functions in the C++ language with the help of simple and easy examples. This tutorial will guide you on how to define a function and various ways to call a function.

A function is a group of instructions that accept inputs, carry out particular calculations, and return results. A function is a collection of statements that execute a specific activity. Every C++ program includes at least one function, main(), and even the simplest programs can declare extra functions. Your code can be broken up into different functions. It is up to you how you divide your code into several functions, but conceptually each function should typically carry out a particular task. A function declaration informs the compiler about a function's name, return type, and parameters. The body of the function is provided by a function definition.

What is the purpose of functions?

  • We can reduce code repetition by using functions. If a software feature needs to be performed in several places, we build a function and call it everywhere rather than writing the same code repeatedly. This also helps with maintenance because we only have to alter one area if we make future modifications to the functionality.
  • Functions help to modularize code. Think of a large file with numerous lines of code. If the code is broken up into functions, it becomes incredibly easy to read and utilize.
  • Abstraction is offered via functions. For instance, we don't need to think about how library functions operate inside when we use them.

Types of  function

Functions are basically of two types:

  1. Standard library 
  2. User-defined
Functions in C++

The Standard Library function or built-in function means a pre-written set of codes by the compiler to perform specific tasks. These are the built-in functions that are defined already in the header files. For example cin to store the input data and cout to display something are the standard library functions defined in the header file iostream. Using the functions memcpy() to copy data from one memory region to another, strcat() to combine two strings, and many more functions are there. Normally all input and output operations including mathematical ones are implemented by the library functions.

Whereas, whereas user-defined functions are written by the programmers and used whenever needed in the course of the program. In order to avoid writing the same code repeatedly for various inputs, the idea is to group together tasks that are frequently or repeatedly performed and turn them into functions that can be called.

Important aspects of a function 

A function in a C++ program becomes complete only when these three important aspects are specified properly. They are:

  1. Function Declaration
  2. Function Definition
  3. Function Call

Function Declaration or Function Prototype in C++

Function Declaration is always a better practice in C language, as it gives a clue to the compiler a function will be used in the program later. Function declaration gives information like the name of the function, the number of parameters used in the function, and the type of function to the compiler. An important point to be considered while declaring a function is that it must be declared globally, which means outside the main() function.

A function declaration can be perceived as an announcement to the compiler that in the future a function will be used in the program. Hence it doesn't have function body.

The syntax of the function declaration is :

returnType function_name(dataType1, dataType2, ...);

Only the type of the parameters is required in a function declaration;

We have given some examples of the function declaration for your reference.

    int max(int, int);

    Above declaration is of a function ‘max’ that takes two integers as parameters and returns an integer value.

    void swap(int, int);

    The swap function takes two parameters of type integer and does not return any value and hence the return type is void.

    void display();

    The function display does not take any parameters and also does not return any type.

    int *swap(int*,int);

    The function that takes an int pointer and an int variable as parameters and returns a pointer of type int

    char *call(char b);

    A function that takes a char and an int as parameters and returns an integer

It is generally advisable to declare a function before using it

Note : The Function declaration should be before the function call.

In C++, we can simultaneously declare and define things, as seen in the above program.

Additionally, C++ enables the declaration and definition of functions independently, which is crucial when dealing with library functions. The header files and library files both include declarations of the library functions. Here is an example of a declaration.

How to define a function in C++?

A function's general form is:

return_type function_name( parameter list ) {
    body of the function

A C++ function definition is made up of two parts: a function header and a function body. The components of a function are listed below:

  • Return Type

    A function may return a value as its return type. The data type of the value returned by the function is specified by the return type. Some functions carry out the desired actions but do not return a value. In this case, the return type is the term void.

  • Function Name: 

    The actual name of the function is indicated by this. The function signature is made up of the function name and the parameter list.

  • Parameters :

    A parameter is similar to a placeholder. The parameter is passed a value when a function is called. This value is known as the real parameter or argument. The type, order, and a number of the parameters of a function are described in the parameter list. A function may or may not have parameters because the parameters are optional.

  • Function Body : 

    The function body is made up of a number of statements that specify what the function does.

Example code for C++ function

The source code for a function called max() is shown below. This function returns the largest value out of two parameters, num1, and num2.

// function returning the max between two numbers

int max(int num1, int num2) {
   // local variable declaration
   int result;

   if (num1 > num2)
       result = num1;
       result = num2;

   return result;

Calling a Function in C++

When you create a C++ function, you define what the function must accomplish. You must call or invoke a function in order to use it.

Program control is passed to the called function when a program calls a function. When a called function completes a specified task, it executes its return statement or reaches the closing brace of its function before returning program control to the main program.

To call a function, simply give the appropriate parameters along with the function name, and if the function returns a value, you can store the returned value.

The syntax is  :


Functions in C++

How function works in C++

In C++, the execution of a program starts with the main() function where the function call is residing. When the compiler comes across a function call, the control will shift to the corresponding function definition where it performs some task designed for it. The final result will be returned to the function call when it encounters a return statement. If not it outputs the result in the function itself and immediately terminates the function to switch the control back to the main() function.

From the above max() function example, function call like this:

max(10, 50);

Example : Maximum of two numbers

#include <iostream>

using namespace std;

// function declaration
int max(int n1, int n2);

int main() {
    // local variable declaration:
    int num1 = 500;
    int num2 = 1000;
    int ret;

    // calling a function to get max value.
    ret = max(num1, num2);
    cout << "Max value is : " << ret << endl;

    return 0;

// function returning the max between two numbers
int max(int n1, int n2) {
    // local variable declaration
    int result;

    if (n1> n2)
        result = n1;
        result = n2;

    return result;

We maintained the max() and main() functions and compiled the source code. The output while executing the final executable would be as follows:


Max value is : 1000

In the above program, we have used a function max that has 2 int parameters.

We then pass num1 and num2 as arguments. These values are stored by the function parameters n1 and n2 respectively.

Functions in C++

Function return statement in C++

The return statement in the C++ language returns a value to the calling function by terminating the execution of its corresponding function. To return a value we must declare a function with any of the valid data types unless can keep it void. In our previous example, the value of a is returned to the main function and is assigned to the variable arc which is visualized below.

Functions in C++

Function Arguments

If a function is going to take arguments, it must declare variables that will accept the arguments' values. These variables are known as the function's formal parameters.

The formal parameters act similarly to other local variables within the function in that they are created upon entry and removed upon exit.

There are three  methods for passing arguments to a function when calling it:

  1. Call by value 
  2. Call by Pointer 
  3. Call by Reference 

Note: Call by value is the default method of passing parameters in C++. This generally indicates that code inside a function cannot change the arguments passed to the function when it is called. In the above example, while calling max() function used the same method.

Please refer to the Function arguments tutorial to get more information about passing arguments.

Main Function in C++

The main function is considered a special function. An essential component of every C++ program is the main function. It acts as the program's starting point. The main function will be the first line of code that the computer runs.

Types of the main Function

  • The main function without parameters
    // Without Parameters
    int main()
      return 0;
  • The main function with parameters
    // With Parameters
    int main(int argc, char * const argv[])
       return 0;

Input from the command line is permitted because the main function has a parameter option.

When you use the main function with parameters, it records every group of characters (separated by a space) after the program name as elements in an array called argv.

Because the return type of the main function is int, the programmer must always include a return statement in the code. The number returned is used to inform the caller program about the outcome of the program's execution. Returning 0 signifies that everything went as planned which means no problems.