Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C++

Learn step by step



Functions

Function is a sub program that acts on data and mostly returns value. Program written with number of functions is easier to update, maintain and debug than one long program. By programming in a modular (functional) way, number of programmers can work independently on separate modules these modules can be assembled later to create the entire project fast and manageable. Every module has its own name. When that name is encountered in program, the program execution goes to the body of that function. When the function is finished, the execution returns to the calling point, and program continues on to the next line of code.

Functions are basic building blocks of programs. They make the programs modular and easy to read and maintain. All C++ programs must contain the function named main( ). The execution of program starts from main( ). A C++ program can contain any number of functions according to the needs. The general syntax of the function is: -

return_type function_name(parameter list)

{

body of the function

}
Function Definition

The syntax for function definition is as follows:

returnValueType functionName ( parameterList ) {
functionBody ;
}

  • The parameterList consists of comma-separated parameter-type and parameter-name, i.e., param-1-type param-1-name, param-2-type param-2-name,...
  • The returnValueType specifies the type of the return value, such as int or double. An special return type called void can be used to denote that the function returns no value. A function is allowed to return one value or no value (void). It cannot return multiple values. [C++ does not allow us to return an array!]

Why Functions?

When a certain portion of codes has to be used many times. So, Instead of re-writing the codes many times, it is better to put them into a "subroutine", and "call" this "subroutine" many time - for ease of maintenance and understanding. Subroutine is called method (in Java) or function (in C/C++).

The benefits of using functions are:

  • Divide and conquer: construct the program from simple, small pieces. Modularize the program into self-contained tasks.
  • Avoid repeating codes: Easy to copy and paste, but hard to maintain and synchronize all the copies.
  • Software Reuse: you can reuse the functions in other programs, by packaging them into library codes.

Two parties are involved in using a function: a caller who calls the function, and the function called. The caller passes argument(s) to the function. The function receives these argument(s), performs the programmed operations within the function's body, and returns a piece of result back to the caller.

Using Functions
Get Started with an Example

Suppose that we need to evaluate the area of a circle many times, it is better to write a function called getArea(), and re-use it when needed.

Fig 1.


/* Test Function (TestFunction.cpp) */
#include <iostream>
using namespace std;
const int PI = 3.14159265;

// Function Prototype (Function Declaration)
double getArea(double radius);

int main() {
double radius1 = 1.1, area1, area2;
// call function getArea()
area1 = getArea(radius1);
cout << "area 1 is " << area1 << endl;
// call function getArea()
area2 = getArea(2.2);
cout << "area 2 is " << area2 << endl;
// call function getArea()
cout << "area 3 is " << getArea(3.3) << endl;
}

// Function Definition
// Return the area of a circle given its radius
double getArea(double radius) {
return radius * radius * PI;
}

Output

area 1 is 3.63
area 2 is 14.52
area 3 is 32.67

In the above example, a reusable function called getArea() is defined, which receives a parameter (in double) from the caller, performs the calculation, and return a piece of result (in double) to the caller. In the main(), we invoke getArea() functions thrice, each time with a different parameter.

In C++, you need to declare a function prototype (before the function is used), and provide a function definition, with a body containing the programmed operations.

The "return" Statement

Inside the function's body, you could use a return statement to return a value (of the returnValueType declared in the function's header) and pass the control back to the caller. The syntax is:

return expression; // Evaluated to the value of returnValueType declared in function's signature
return; // For function with return type of void

Take note that invoking a function (by the caller) transfers the control to the function. The return statement in the function transfers the control back to the caller.

Function Naming Convention

A function's name shall be a verb or verb phrase (action), include one or more words. The first word is in lowercase, while the rest are initial-capitalized (known as camel-case). For example, getArea(), setRadius(), moveDown(), isPrime(), etc.

Function Prototype

In C++, a function must be declared before it can be called. It can be achieved by either placing the function definition before it is being used, or declare a function prototype..

A function prototype tells the compiler the function's interface, i.e., return-type of the function,name of the function, and parameter type list (the number and type of parameters). Function can be defined now anywhere in the file.

// Function prototype - placed before function is used.
double getArea(double); // without the parameter name
int max(int, int);

We could optionally include the parameter names in the function prototype. Names will be ignored by the compiler, but serve as documentation. For example,

// Function Prototype
double getArea(double radius); // parameter names are ignored, but serve as documentation
int max(int number1, int number2);

Prototypes of function are grouped together and placed in a header file.

The "void" Return Type

Suppose that we need a function to perform certain actions without need to return a value to calling point, we can declare its return-value type as void. In function's body, we could use a "return;" statement without a return value to return control to the caller. In that case, the return statement is optional. If there is no return statement, entire body of the function will be executed, and then after control returns to the calling point at the end of the body.

Arguments passed by value & passed by reference

There are 2 ways that a parameter can be passed into a function:
pass by value vs. pass by reference.

Pass-by-Value

In this mechanism copies of the arguments are created and are stored in the temporary locations of memory. Parameters are mapped to the copies of the arguments created. Changes made to parameter do not affect the original arguments. It provides security to the calling program. E.g.,


#include<iostream>

using namespace std;

int add(int n);



int main()

{

int number,result;

number=5;

cout << " The initial value of number : " << number << endl;

result=add(number);

cout << " The final value of number : " << number << endl;

cout << " The result is : " << result << endl;

return(0);

}



int add(int number)

{

number=number+100;

return(number);

}

Output

The initial value of number : 5
The final value of number :5
The result is :105

Value of the variable number before calling the function is 5. Function call is made & function adds 100 to the parameter number. When function is returned the result contains the added value. Final value of number remains same as 5. This shows that operation on parameter doesn't produce effect on original arguments.

Pass by reference

Pass by reference is the another way of passing parameters to the function. Address of the argument is copied into the parameter. Changes made to the parameter affect the original arguments. Address of the argument is passed to the function and function modifies the values of arguments in the calling function. E.g.,


#include<iostream>

using namespace std;

int add(int &number);



int main ()

{

int number;

int result;

number=5;

cout << "The value of the variable number before calling the function : " << number << endl;

result=add(&number);

cout << "The value of the variable number after the function is returned : " << number << endl;

cout << "The value of result : " << result << endl;

return(0);

}



int add(int &p)

{

*p=*p+100;

return(*p);

}

Output

The value of the variable number before calling the function : 5
The value of the variable number after the function is returned :105
The value of result :105

The address of variable is passed to the function. p points to memory address of variable number. It changes actual contents of the variable(number). Value of variable number before calling of the function is 100 and after function is returned the value is changed to 105.

Default values in parameters

Functions can also have optional parameters in C++, In that no arguments are required in the function call, in such a way that, E.g., a function with 3 parameters may be called with only two. For this, function shall include a default value for its last parameter, which is used by function when called with fewer arguments.
Example:


// default values in functions
#include <iostream>
using namespace std;

int divide (int a, int b=2)
{
int r;
r=a/b;
return (r);
}

int main ()
{
cout << divide (12) << '\n';
cout << divide (20,4) << '\n';
return 0;
}

Output

6
5

In the example, there are 2 calls to function divide. First one:

divide (12)

This call passes only one argument to the function, even though the function has more than one parameters. In that case, the function assumes the second parameter to be 2 (Note; function definition, which declares second parameter as b=2). So, the result is 6.

In second call:

divide (20,4)

This call passes two arguments in the function call. So, the default value for b (int b=2) is ignored, and b takes the value passed in the call, that is 4, yielding a result of 5.

Function Overloading

C++ introduces function overloading (also called as function polymorphism, which means many forms), this allows us to have multiple versions of the same function name, differentiated by parameter list (it can be differ in number, type or order of parameters). The version matches caller's argument list will be selected for the execution.
Example,


/* Test Function Overloading (FunctionOverloading.cpp) */
#include <iostream>
using namespace std;

void fun(int, int, int); // Version 1
void fun(double, int); // Version 2
void fun(int, double); // Version 3

int main() {
fun(1, 2, 3); // version 1
fun(1.0, 2); // version 2
fun(1, 2.0); // version 3
fun(1.1, 2, 3); // version 1 - double 1.1 casted to int 1 (without warning)

// fun(1, 2, 3, 4);
// error: no matching function for call to 'fun(int, int, int, int)'
// fun(1, 2);
// error: call of overloaded 'fun(int, int)' is ambiguous
// note: candidates are:
// void fun(double, int)
// void fun(int, double)
// fun(1.0, 2.0);
// error: call of overloaded 'fun(double, double)' is ambiguous
}

void fun(int n1, int n2, int n3) { // version 1
cout << "version 1" << endl;
}

void fun(double n1, int n2) { // version 2
cout << "version 2" << endl;
}

void fun(int n1, double n2) { // version 3
cout << "version 3" << endl;
}

Overloaded functions can't be differentiated by their return-type (compilation error).

Recursivity

It is the property that functions have to be called by themselves. It is useful for some tasks, like sorting elements, or calculating the factorial. E.g., in order to obtain the factorial of a number (n!) the mathematical formula would be:

n! = n * (n-1) * (n-2) * (n-3) ... * 1
Or we can say, 5! would be:
5! = 5 * 4 * 3 * 2 * 1 = 120
A recursive function to calculate this:


// factorial calculator
#include <iostream>
using namespace std;

long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return 1;
}

int main ()
{
long number = 9;
cout << number << "! = " << factorial (number);
return 0;
}

Output

9! = 362880

Notice: In function factorial we included a call to itself, but only if the argument passed was greater than 1, since, otherwise, function would perform an infinite recursive loop, in condition once it arrived to 0, it would continue multiplying by all the negative numbers (probably provoking a stack overflow at some point during the runtime).



Related Videos