Functions in C++

Functions are used to provide modularity to the program.Creating an application using functions makes it easier to understand, edit and check errors.

What is  function?

  A large C program is divided into basic building blocks called C function. C function contains set of instructions enclosed by “{  }” which performs specific operation in a C program. Actually, Collection of these functions creates a C program.

 Uses of  functions:

  • C functions are used to avoid rewriting same logic/code again and again in a program.
  • There is no limit in calling C functions to make use of same functionality wherever required.
  • We can call functions any number of times in a program and from any place in a program.
  • A large C program can easily be tracked when it is divided into functions.
  • The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve the functionality and to improve understandability of very large C programs.

Types of  functions

There are two types of functions in C programming:

  • Library function
  • User defined function

Library function

Library functions are the in-built function in C programming system. For example:


– The execution of every C program starts from this main() function.


prinf() is used for displaying output in C.


scanf() is used for taking input in C.


User defined function

C allows programmer to define their own function according to their requirement. These types of functions are known as user-defined functions. Suppose, a programmer wants to find factorial of a number and check whether it is prime or not in same program. Then, he/she can create two separate user-defined functions in that program: one for finding factorial and other for checking whether it is prime or not.



Advantages of user defined functions

  1. User defined functions helps to decompose the large program into small segments which makes programmer easy to understand, maintain and debug.
  2. If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function.
  3. Programmer working on large project can divide the workload by making different functions.

Syntax of function

Functions that a programmer writes will generally require a prototype. Just like a blueprint, the prototype tells the compiler what the function will return, what the function will be called, as well as what arguments the function can be passed.

For example:

ReturnType FunctionName(parameter list);
//function body

Return-type: Gives the type of data that  that the function returns. A function may return any type of data except an array. In variable declarations, you can declare many variables to be of a common type by using a comma-separated list of variable names. In contrast, all function parameters must be declared individually, each including both the type and name. That is, the

Function-name: It is the name of the function. Usually function names are verbs specifying the action they will perform when called in the main program(function).

Parameters list: The parameter list is a comma-separated list of variable names and their associated data types that receive the values of the arguments when the function is called. A function may be without parameters, in which case the parameter list is empty. However, even if there are no parameters, the parentheses are still required.

Passing Arguments to a Function:

  1. In C Programming we have different types of parameter passing schemes such as Call by Value and Call by Reference.
  2. Functions are reusable codes which can be called whenever required.
  3. Whenever we call a function that sequence of executable code gets executed .
  4. We can pass some of the information to the function for processing called Arguments.

Ways of passing Arguments to function

  1. Call by Value
  2. Call by reference.


Call by Value

  •  When passing Parameters using Call by Value,xerox copy of original parameters is created and passed in the called function.
  • Any update made inside the method won’t affect the original value of variable in calling functionCall-by-Value-in-C-Programming-Scheme-300x226
  • In the above example,num1 is the original values and xerox copy of this values is passed to the function and this values are copied as number1  variables of the function .
void interchange(int number1, int number2)
    int temp;
    temp = number1;
    number1 = number2;
    number2 = temp;
int main()
    int num1 = 50 , num2 = 70 ; 
    interchange ( num1 , num2 ) ;
    cout<<"\nNumber 1 : %d"<<num1;
    cout<<"\nNumber 2 : %d"<<num2;
    return 0;

Output :

Number 1 : 50
Number 2 : 70

void interchange(int number1,int number2)
    int temp;
    temp = number1;
    number1 = number2;
    number2 = temp;

int main() {

    int num1=50,num2=70;

    cout<<"\nNumber 1" <<num1;
    cout<<"\nNumber 2 "<<num2;


Output :

Number 1 : 50
Number 2 : 70

Explanation : Call by Value

  1. While Passing Parameters using call by value , xerox copy of original parameter is created and passed to the called function.
  2. Any update made inside method will not affect the original value of variable in calling function.
  3. In the above example num1 and num2 are the original values and xerox copy of these values is passed to the function and these values are copied into number1,number2 variable of sum function respectively.
  4. As their scope is limited to only function so they cannot alter the values inside main function.


Call by Reference/Pointer/Address :

Explanation : Call by Reference

  1. While passing the parameters by reference we pass the actual address of the parameter ,no copy of the parameter is made in the function.
  2. Any updates made in the function will modify the original copy since we are directly modifying the content of exact memory location.

void interchange(int *num1,int *num2)
    int temp;
    temp  = *num1;
    *num1 = *num2;
    *num2 = temp;

int main() {

    int num1=50,num2=70;

    cout<<"\nNumber 1" <<num1;
    cout<<"\nNumber 2"<< num2;


Output :

Number 1 : 70
Number 2 : 50


Calling Functions with Arrays

Passing arrays as arguments to functions is different than  the normal call-by-value  parameter passing.When an array is used as a function argument, its address is passed to a function.As the address and not the copy is passed any update made inside the method  affects the original value of array in calling function .

Passing Entire 1-D Array to Function in C Programming

  • Array is passed to function Completely.
  • Parameter Passing Method : Pass by Reference
  • It is Also Called “Pass by Address
  • Original Copy is Passed to Function
  • Function Body Can Modify Original Value.
  • Example :

For example:

void fun(int arr[])
int i;
for(i=0;i< 5;i++)
 arr[i] = arr[i] + 10;

void main()
int arr[5],i;
cout<<"\nEnter the array elements : ";
for(i=0;i< 5;i++)

cout<<"\nPassing entire array .....";
fun(arr);  // Pass only name of array

for(i=0;i< 5;i++)
 cout<<"\nAfter Function call a[%d] : %d"<<i<<arr[i];

Output :

Enter the array elements : 1 2 3 4 5

Passing entire array .....
After Function call a[0] : 11
After Function call a[1] : 12
After Function call a[2] : 13
After Function call a[3] : 14
After Function call a[4] : 15

Graphical Flowchart :

Returning from a Function

  1. The return Statement causes an immediate exit from the function that it is in. That is, it causes program execution to return to the calling code.
  2. Second, it may be used to return a value.
  3. A function may have more than one return statements but only one of them gets executed depending which is encounter first and also satisfies the given conditions. 

There are two ways that a function terminates execution and returns to the caller. The first occurs when the last statement in the function has executed and, conceptually, the function’s ending curly brace ( } ) is encountered.

A function can have following return type:

  1. Void
  2. Non Void i.e of the type int,float ,char etc..


Void Functions

A function that does not return a value is declared and defined as void. Here is an example:

void Introduction()
	cout << "This program is used to calculate the areas of some shapes.\n"
	     << "The first shape will be a square and the second, a rectangle.\n"
	     << "You will be requested to provide the dimensions and the program "
             << "will calculate the areas";

Any function could be a void type as long as you are not expecting it to return a specific value.

  1.  When a function is of type void, it cannot be used on the same line with the cout extractor and it cannot be assigned to a variable (since it does not return a value).
  2. Therefore, a void function can only be called.

 Non-Void Function

A return value, if not void, can be any of the data types we have studied so far. This means that a function can return a char, an int, a float, a double, a bool, or a string.

  1. If you declare a function that is returning anything (a function that is not void), the compiler will need to know what value the function will return. The return value must be the same type declared. The value is set with the return keyword.
  2. If a non-void function does not explicitly return a value via a return statement, then a garbage value is returned. In C++, a non-void function must contain a return statement that returns a value.

for example:

string GetMemberName()
	string FName, LName, FullName;	

	cout << "New Member Registration.\n";
	cout << "First Name: ";
	cin >> FName;
	cout << "Last Name: ";
	cin >> LName;

	FullName = FName + " " + LName;
	return FullName;
  1. The return value can also be an expression.
  2. A return value could also be a variable that represents the result.
  3. If a function returns a value (other than void), a calling function can assign its result to a local variable like this:
    Major = GetMajor();
  4. You can also directly display the result of a function using the cout operator. In this case, after typing cout and its << operator, type the function name and its arguments names, if any.

In C++, a function should always display a return type, otherwise, make it void. If you declare a function without a return type, by default, the compiler considers that such a function should return an integer. Therefore, the main() function we have used so far should return an integer as follows:

#include <iostream>
using namespace std;

int main()
	cout << "This is C++ in its truest form...\n\n";
	return 0;

Strictly stated, the main() function can return any integer, which simply indicates that the program has ended. Returning 0 means that the program has terminated successfully. Since the main() function now returns an integer, you should indicate this on its declared line. A better version of the above main() function would be:

#include <iostream>
using namespace std;

int main()
	cout << "This is C++ in its truest form...\n\n";
	return 0;

What Does main( )  Return in C++?

The main() function returns an integer to the calling process, which is generally the operating system. Returning a value from main() is the equivalent of calling exit() with the same value. If main() does not explicitly return a value, the value passed
to the calling process is technically undefined. In practice, most C/C++ compilers automatically return 0, but do not rely on this if portability is a concern.

Function prototype

In C++ all functions must be declared before they are used. This is accomplished using function prototype.The function prototype is placed outside any function including “main”, right after the “#include” preprocessor directive. That’s why function prototype has file scope.

  1. Prototypes enable compiler to provide stronger type checking.
  2. When prototype is used, the compiler can find and report any illegal type conversions between the type of arguments used to call a function and the type definition of its parameters.
  3. It can also find the difference between the no of arguments used to call a function and the number of parameters in the function. Thus function prototypes help us trap bugs before they occur.
  4. In addition, they help verify that your program is working correctly by not allowing functions to be called with mismatched arguments.

The general form of a function prototype is

type func_name(type parm_name1, type parm_name2,. . .,type parm_nameN);

The use of parameter names is optional.

void sqr_it(int *i);      //prototype of function sqr_it
int main()
        int num;
        num = 10;
        sqr_it(num);       //type mismatch
        return 0;
void sqr_it(int *i)
          *i = *i * *i;

Since sqr_it() has pointer to integer as its parameter, the program throws an error when we pass an integer to it.

Default Arguments

When the arguments you pass to the called function are most probably of some definite values, you can specify these values in the function prototype. When the values of the parameters are the default ones, you can omit the parameters.

int void count(int  x = 1, int  y = 1, int  z = 1)
int  main ( )
            count (2, 3);

When you use a function with an argument list, you must add defaults from right to left. That is, you can’t provide a default value for a particular argument unless you also provide defaults
for all the arguments to its right:

int  harpo(int n, int m = 4, int j = 5); // VALID
int  chico(int n, int m = 6, int j); // INVALID
int  groucho(int k = 1, int m = 2, int n = 3); // VALID
For example, the harpo() prototype permits calls with one, two, or three arguments:
beeps = harpo(2); // same as harpo(2,4,5)
beeps = harpo(1,8); // same as harpo(1,8,5)
beeps = harpo (8,7,6); // no default arguments used
The actual arguments are assigned to the corresponding formal arguments from left to right;
you can’t skip over arguments. Thus, the following isn’t allowed:
beeps = harpo(3, ,8); // invalid, doesn’t set m to 4

Returning Pointers

Pointers are the  variables which hold the memory addresses of a certain type of data. To return a pointer, a function must be declared as having a pointer return type.

Before the closing curly bracket of the function, remember to return a pointer to the return the value. Here is an example:

double * GetSalary()
    double salary = 26.48;
    double *HourlySalary = &salary;
    return HourlySalary;

Because a pointer by defining is a reference to the address where a variable resides, when a function is defined as returning a pointer, you can also return a reference to the appropriate type. Here is an example:

double * GetSalary()
    double salary = 26.48; 
    return &salary;

Recursive Functions

A function defined in terms of itself is called a recursive function. Recursive function is a function which contains a call to itself. An example of Recursive Function is factorial of a number.The factorial of a number n is the product of all the whole numbers between 1 and n. For example, 5 factorial is 5 *4*3*2*1

/* recursive version */
int factorial(int n)
    return( n * factorial(n-1));
/* non-recursive */
int fact(int n)
 int t, answer;
 answer = 1;
 for(t=1; t<=n; t++)


Key points of Recursive Functions:


  1. Recursive function must have at least one terminating condition that can be satisfied.
  2. It should know the condition under which it has to call itself again.
  3. Otherwise, the recursive function will call itself repeatably until the run time stack overflows.

Inline Function

Inline are the special functions whose main purpose is to save time at a cost in space. Once you define an inline function, using the ‘inline’ keyword, whenever you call that function the compiler will replace the function call with the actual code from the function.

  1. All the member functions defined inside the class definition are by default declared as inline.
  2. inline functions are the actual functions which are copied everywhere during compilation,like pre-processor macros,so the overhead of function calling is reduced.
  3. You can make any non-c;ass function inline by using keyword inline with them.
  4. for an inline function declaration and definition is done together.

Inline code is faster than a function call for two reasons. First, a CALL instruction takes time to execute. Second, if there are arguments to pass, these have to be placed on the stack, which also takes time. For example,

#include <iostream>
using namespace std;

inline void hello()
int main()
  hello(); //Call it like a normal function...

However, once the program is compiled, the call to hello(); will be replaced by the code making up the function.

Important points about Inline Functions:

  1. We must keep inline functions small.Small inlin functions have better efficiency.
  2. Inline functions do increase efficiency, but we should not make all the functions inline because if we make all the functions inline ,it may lead to code bloat and might affect the speed also.
  3. Hence,we must not define large function inside class definition as they become inline instead we must define them outside class using scope resolution operator.