Functions in C++ Programming

Function is a logically grouped set of statements that perform a specific task. For example, a function sort() may sort a group of data. Every C++ program has a function named main() where the execution of the program starts. It is a mandatory function in C++.

  1. Advantages of Function
  2. Components of Function
  3. Types of Function
  4. Static Member Function

Advantages of Function

Creating functions in a program is beneficial. They

  • Avoid repetition of codes.
  • Increase program readability.
  • Divide a complex problem into many simpler problems.
  • Reduce chances of error.
  • Makes modifying a program becomes easier.
  • Makes unit testing possible.

Components of Function

A function usually has three components. They are:

  1. Function prototype/declaration
  2. Function definition
  3. Function call

1. Function prototype/declaration

Function declaration informs the compiler about the function’s name, type and number of argument it receives and type of value it returns.

Syntax for function declaration

returntype function_name ([arguments type]);

For example,

void display(char); /*function name = display, receives a character 
                      as argument and returns nothing*/
int sum(int,int); /*function name = sum, receives two integers 
                    as argument and returns an integer*/

2. Function definition

It is the most important part of function which that consists of body of function. It consists of block of statements that specifies what task is to be performed. When a function is called, the control is transferred to the function definition.

Syntax for function definition

returntype function_name ([arguments])
{
    statement(s);
    ... ... ...
}

Return Statement

Function can return values. A return statement is used to return values to the invoking function. The type of value a function can return is specified in the function prototype. A function which has void as return type don’t return any value. Beside basic data type, it can return object and pointers too. A return statement is usually place at the end of function definition or inside a branching statement.

For example,

int sum (int x, int y)
{
    int s = x+y;
    return s;
}

In this function, the return type of sum() is int. So it returns an integer value s to the invoking function.

3. Function call

Function call statement calls the function by matching its name and arguments. A function call can be made by using function name and providing the required parameters.

Syntax for function call

function_name ([actual arguments]);

For example,

display(a);

s = sum(x,y);

A function can be called by two ways. They are:

  • Call by value
  • Call by reference

Call by value

When a function is called, the called function creates a copy of all the arguments present in the calling statement. These new copies occupy separate memory location and the function works on these copies only. This method of calling a function is called call by value. In this method, only the value of argument is passed. So, if any changes done to those values inside the function is only visible inside the function. Their values remain unchanged outside it.

Example 1: C++ program to determine a number is even or odd using function (call by value)

#include <iostream>
#include <conio.h>
using namespace std;

int iseven(int); // function prototype

int main()
{
    int n;
    cout<<"Enter a number: ";
    cin>>n;
    if (iseven(n)) // function call by value
        cout<<n<<" is even";
    else
        cout<<n<<" is odd";
    getch();
    return 0;
}

int iseven(int x) // function definition
{
    int r;
    if (x%2 == 0)
        r=1;
    else
        r=0;
    return r;
}

In this program, a number is entered by user which is passed as parameter to a user-defined function iseven(). It receives the integer value and returns 1 if it is even, otherwise returns 0.

Output

Enter a number: 16
16 is even
Enter a number: 31
31 is odd

Call by reference

In this method of calling a function, the reference of argument is passed rather than its value. The argument received by the function and the actual argument occupy same memory addresses. So, if any changes done to those values inside the function is also visible both inside and outside the function.

For example, consider a function swap(int,int) which receives two integer arguments and swap their values. If this function is called by value then the changes in value of variables after swapping won’t be seen outside the function. This problem can be solved by calling the function by reference.

Example 2: C++ program to swap two values using function (call by reference)

#include <iostream>
#include <conio.h>
using namespace std;

void swap(int &, int &); // function prototype

int main()
{
    int a,b;
    cout<<"Enter two numbers: ";
    cin>>a>>b;
    cout<<"Before swapping"<<endl;
    cout<<"a = "<<a<<endl;
    cout<<"b = "<<b<<endl;
    swap(a,b); // function call by reference
    cout<<"After swapping"<<endl;
    cout<<"a = "<<a<<endl;
    cout<<"b = "<<b<<endl;
    getch();
    return 0;
}

void swap(int &x, int &y) // function definition
{
    x=x+y;
    y=x-y;
    x=x-y;
}

This program swaps the value of two integer variables. Two integer values are entered by user which is passed by reference to a function swap() which swaps the value of two variables. After swapping these values, the result is printed.

Output

Enter two numbers: 19 45
Before swapping
a = 19
b = 45
After swapping
a = 45
b = 19

Types of function

There are two kinds of function. They are:

  1. Library functions
  2. User-defined functions

1. Library functions

Library functions are built in function that are defined in the C++ library. Function prototype is present in header files so we need to include specific header files to use library functions. These functions can be used by simply calling the function. Some library functions are pow(), sqrt(), strcpy(), toupper(), isdigit(), etc.

2. User-defined functions

These functions are defined by user as per the requirement, hence called user-defined functions. Function definition is written by user and is present in the program. main() is an example of user-defined function.

Static Member Function

In C++, functions are defined inside a class and can only be accessed by its object. But when a class has a private static data member (variable), these cannot be accessed directly, so we need a function specifically to access those data members, these are static member functions. They are defined/declared using keyword static before their name.
We can also define a static function outside a class declaration. These act similar to normal functions.

Syntax of Static Member Function

static returntype function_name ([argument list])
{
    body of function
}

Properties of Static Member Function

  1. A static member function can access only other static data members declared in that class.
  2. We do not need to create class objects to access these functions. They can be accessed directly using class name and scope resolution operator (::) instead of object of the class.
    classname::function_name ([actual argument]);
  3. A static member function cannot be virtual.

Example 3: C++ program to use a static member function

#include<iostream>
#include<conio.h>
using namespace std;

class test
{
    static int x;
    int id;
    public:
        test()
        {
            x++;
            id=x;
        }
        static void static_display()
        {
            cout<<"x = "<<x<<endl;
        }
        void display()
        {
            cout<<"id= "<<id<<endl;
        }
};

int test::x;

int main()
{
    test o1,o2;
    test::static_display();
    o1.display();
    test::static_display();
    o2.display();
    getch();
    return 0;
}

This program is similar to the previous program but here we have used static member function to display the content of static data member. Static member function are called using class name and scope resolution operator (::) as called in the program:

test::static_display();

Since, static member function can’t access other members of a class except static data member, so a separate function is used to display them.

Output

x = 2
id= 1
x = 2
id= 2