C++ Functions

A function is a self defined block of statements that performs specific tasks for some time. A function is an assignment or a task that must be performed to complement the other part(s) of a program. Every C or C++ program has at least one function which is main(),  you can define your own functions as well.

You can divide up any problem into smaller blocks or functions, you can define its functionality at your own, but logically the divisions should be such that it perform some task. There are also many library functions provided within your library as well, you can also use such in-built functions to shorten your code. Some of the in built functions are- sqrt(), pow(), strcpy () etc.

How to use functions ?

The general form of a C++ function definition is as follows:

return_type function_name( parameter list )

{

body of the function

}

A C++ function definition consists of a function header and a function body. The basic components of functions are:

1. Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void otherwise we can use int or float ets depending upon our need.    General syntax:

                        ReturnType FunctionName();

                   Example: void FunctionName();

                                 double FunctionName();

                                 char FunctionName();

                                 bool FunctionName();

                                 string FunctionName();

2. Function Name: To use any function, you have to give it a name. Naming guidelines are the same that we follow in variable declaration. In addition, use a name that specifies what the function is expected to do. In addition it is advisable to take the appropriate names for functions, like if we are adding two numbers then name would be add or sum. Although it is not mandatory but it gives you easy revision when you recall it and also useful in code re-usability.

3. Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

4. Function Body:

Before using any function in your program, you have to let the compiler know what the function does. To let the compiler know what the function is meant to do, you have to “define” it; which also means describing its behavior. The formula to define a function is:

void FunctionName() {Body}

You define a function using the rule we applied with the main() function. Define it starting with its return value (if none, use void), followed by the function name, its argument (if any) between parentheses, and the body of the function. Once you have defined a function, other functions can use it.

Function Body

As an assignment, a function has a body. The body of the function describes what the function is supposed to do. The body starts with an opening curly bracket “{“ and ends with a closing curly bracket “}”. Everything between these two symbols belongs to the function. From what we have learned so far, here is an example:

void Display() {};

In the body of the function, you describe the assignment the function is supposed to perform. As simple as it looks, a function can be used to display a message. Here is an example:

void Display(){ cout << ” I like csetips “;}

A function can also implement a complete behavior. For example, on a program used to perform geometric shape calculations, you can use different functions to handle specific tasks. Imagine you want to calculate the area of a square. You can define a particular function that would request the side of the square:

}

Calling Functions

Now after defining the functions, the other job is to call a function. One of the main reasons of using various functions in your program is to isolate assignments; this allows you to divide the jobs among different entities so that if something is going wrong, you might easily know where the problem is. One function simply needs to know what the other function does, and what that other function needs.

Once a function has been defined, other functions can use the result of its assignment.   Let we have two functions A and B.

If Function A needs to use the result of Function B, function A has to use the name of function B. This means that Function A has to “call” Function B:

When calling one function from another function, provide neither the return value nor the body, simply type the name of the function and its list of arguments, if any. For example, to call a function named Welcome() from the main() function, simply type it, like this:

int main()

{

        Display(); // Calling the Display () function

        return 0;

}

The compiler treats the calling of a function depending on where the function is declared with regards to the caller. You can declare a function before calling it. Here is an example:

#include <iostream>

using namespace std;

void Display()

{

        cout << “I like csetips “;

}

int main()

{

        Display(); // Calling the Display() function

        return 0;

}

Calling a Function Before Defining it (without any arguments)

The example we saw above requires that you define a function before calling it. C/C++, like many languages, allows you to call a function before defining it. Unlike many languages, in C++, when calling a function, the compiler must be aware of the function. This means that, you must at least declare a function before calling it. After calling the function, you can then define it as you see fit. Here is an example:

#include <iostream>

using namespace std;

 int main()

{

        void Display();

        cout << ” Learn C++ “;

        Display (); // Calling the Display () function

        return 0;

}

 void Display ()

{

        cout << ” I like csetips “;

}

 Function Arguments:

In the last program, we have only learnt how to call a function. In previous code we use simple Display (). We can also send arguments or parameters in the function. The arguments in the calling function is called actual arguments. If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways that arguments can be passed to a function:

Call Type Description
Call by value This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Call by pointer This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
Call by reference This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.