7 Functions in C++ I
Jyoti Pareek
Functions
Functions in C++, offer similar solution for organizing large and complex program. While writing a program, the main program becomes too large and complex if programmer writes all the steps within it. The readability of program also turns to be complex. Testing or debugging becomes quite difficult. Instead, if he collects certain steps, for example finding square root or displaying record on the screen, bundles them in a routine and writes them in either a separate file or same file outside the main() function, the main programme would look much simpler. Functions facilitates partitioning a complex problem into set of sub-problems which are easily understandable, maintainable and manageable. Once the problem is divided into set of tasks, we can write function for each task. Each function implements a small task or particular aspect of a large program. A complete application can then be developed integrating all such functions.
Function can be defined as a group of statements that is given a unique and meaningful name within a program. It is created to perform a specific task.
Every C++ program has at least one function, which is main().One can define more functions as per the need.
Functions in C++ are very similar to functions in C except the return type default. The default return type in C is int whereas default return type in C++ is void. There are three steps to create and use a
function in C++ program.
1. Declaring a function
2. Defining a function
3. Calling a function
Let us understand generalized structure of declaring, defining and calling a function along with an example. Assume that function to calculate xy is intended, where x and y would be given by a user. Function would be given two values as input, x and y and it would return xy as a result.
Declaring a function
Declaration of a function includes stating to a compiler that the declared function is defined in the program, or its object module will be made available at the time of linking . Declaring a function is also known as function prototyping. In C++, function prototyping is mandatory. Compiler error would be raised if a function is called without its prototype mentioned in the program before calling of the function. If a programmer writes a function to add two integers, It can be named as add and prototype of which can be written as int add(int , int). This prototype specifies that add is a function which takes two integers as input and returns an integer value, which in this case will be sum of the given numbers. A function prototype is useful while checking whether the function when called is called with correct set of arguments. And the knowledge of return type will help compliler determine, that the call to the function is placed at correct place or not.
Defining a Function
Defining function means implementing the function. The basic syntax for defining any function in C++ is: returnDataType functionName(dataType argument 1, dataType argument 2……… dataType argument n)
{
function statements;
}
- returnDataType is the datatype of the value function would return back to the point where it is called. If function does not return any value, only control is returned back to the calling function. Return datatype in this case will be defined as void.
- functionName is the identifier by which the function would be referred/called.
- Parameters in the comma-separated list bound by the parentheses specifies argument along with the data type, that would be passed to the function from the calling function. To compute xy, the syntax to declare a function would be as follows:
int power(int, int);
To compute xy, the syntax to define a function and its steps would be as follows:
int power(int base, int exponent)
{
int result=1;
for (int i=1 ; i <= exponent; i++)
{
result=result * base;
}
return result;
}
In the above function, two integers are accepted by the function as per its definition, which are stored in base and exponent. The variable result is local variable with its scope limited to the function power. It is initialized to 1. A for-loop is written to multiply the number stored in base, exponent times. The final answer is stored in variable result.
Note the return statement of the function. In the above mentioned function statements return, returns result to the point where it would be called. A function at a time can return only a single value. Return statement is also an exit statement of function. Once the return statement is executed control would return to the calling point of the function and no other statements following return statement would be executed. Programmer should carefully find out the place where he expects exit from the function. If return statement is not mentioned all the sequential steps of the function would be executed and control would be returned back to the calling point.
Calling a function
We have seen how to declare a function and define a C++ function. However steps inside the function body would never execute until they are called. To use a function, we will have to call or invoke that function. When a program calls a function, program control is transferred to the called function. This is known as context switching. As mentioned earlier, a called function would performs defined steps mentioned in function body and when its return statement is executed or control reaches the end of the function, program control is returned back to the main program. To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example:
The basic syntax for calling any function in C++ is:
result = functionName(actual arguments 1, actual argument 2, actual argument 3…..)
where,
- result is a variable of datatype same as that of function return type specified in function declaration.
- FunctionName should be same as mentioned at the time of declaration
- List of actual arguments includes list of parameters required for execution of steps mentioned in the function body at the time of definition.
To compute xy, the syntax to call a function and its steps would be as follows:
answer = power (x, y);
Advantage of Functions
- Intellectual Manageability
- Modular Design
- Abstraction
- Readability
- Supports Stepwise refinement approach to program development
- Reusability
Disadvantage of Using Functions
Function call generates executional overhead due to context switching. To understand this we need to understand what is context of the function and what is context switching.
Context of Function
Values held in CPU registers, values of parameters and local variables at a given point of time forms the context for executing function/program. When the execution of one function gets suspended for the execution of another function, it results into context switching.
Context Switching
On function call
- Saving the context of calling program.
- Shifting control to called program
On Completion of execution of called program
- Returning the control to calling program.
- Restoring the context of calling program.
Context switching generates executional overhead but the advantages of function are significant and overpowering, hence this disadvantage of function can be ignored.
Also for simple functions this advantage can be overcome in C++ by declaring the function inline.
Inline Functions
Inline functions are functions for which call to a function is replaced by the code of called function at compile time. Therefore no function call is made at runtime, hence no executional overhead. However there will be some increase in the size of executable file. A function can be defined as inline by prefixing keyword inline to the function header.
Module 8 – Functions in C++ I
inline swap(int &num1, int &num2)
{
int temp;
temp = num1;
num1 = num2;
num2 = temp;
}
void main()
{
int x=10, y=20;
……………….
………………..
swap(x,y)
…………….
…………….
}
Limitation of Inline Function
All functions can not be made inline. The request to make function inline will be ignored in the following cases:Too large or too Complex function. Recursive function.
Function having Static Variable.
………….
………….
Functions which are defined inside the class will automatically be considered for making them inline. If they are eligible( i.e they are not recursive, do not have static variables etc) to become inline they will be made inline.
class Time
{
int hours;
int minutes;
int seconds;
public : | |
void readTime(); | // will be made inline |
{ | |
cin >> hours; | |
cin >> minutes; | |
cin >> seconds; | |
} |
Module 8 – Functions in C++ I | |
void displayTime(); | // will be made inline |
{ | |
cout << hours; | |
cout << minutes; | |
cout << seconds; | |
} |
};
Member functions defined outside the class can also be made inline by prefixing keyword inline to the function header.
class Time
{
int hours;
int minutes;
int seconds;
public :
void readTime();
void displayTime();
};
Inline void Time :: readTime();
{
// will be made inline
cin >> hours;
cin >> minutes;
cin >> seconds;
}
inline void Time :: displayTime();
{
// will be made inline
cout << hours;
cout << minutes;
cout << seconds;
}
};
Non inline functions may be defined after its call but inline function must be fully defined before the call.
Parameter Passing in C++ Functions
The parameters passed in C++ functions can be of any data type including objects, pointers and references. Also Functions can return any data type except arrays including objects, pointers and references.
In C++ except array all the data types by default are passed as values. In C we used pointers to achieve the effect of call by reference parameter passing. In C++ we can use pointers and reference variables to achieve the effect of call by reference parameter passing. We discussed all this in detail in Module 4.
Returning reference from C++ variables
In C++ we can also return references from the functions
int &max( int &x, int &y)
{
If ( x > y )
return x;
else
return y;
}
void main()
{
Int value1, value2;
Int maxvalue;
maxvalue = max(value1,value2);
}
More interestingly we can place the function call to a function returning reference variable at the left hand side of operation. For example
We write following statement
max( value1, value2) = 20;
This statement will assign 20 value1 or value2 depending on which one is larger.
Static Functions
Similar to static member variables, static member functions are not attached to any particular object, but remains common to a class. Following program demonstrates usage of static member function update_maxmarks(), which generates roll number which is next to previous generated roll no. Here it can be observed that static member function update_maxmarks(), access static integer max_marks() and updates it with the value provided as parameter. What is noticable is the ways it has been called in the main function. Although it seems that update_maxmarks(), is member function of Student class and hence can be called only if any object of Student class is created, it has been called without any object creation only by using class name as its prefix.
class student
{
int rollno;
char name[20];
int marks_obtained;
static int max_marks;
public :
void readdata();
void displaydata();
int computePercentage();
static int update_maxmarks(int mks) { total_marks = mks;}
};
// Initialize static data member int student :: max_marks = 0;
Restrictions on static member Functions
- They do not get this pointer implicitly passed
- They cannot access not static data member of the class
- They cannot be virtual
- They cannot be const or volatile.
Const Function
Const member function is a function which cannot modify data members of the class.
class Time
{
int hours;
int minutes;
int seconds;
public :
void readTime()
{
cin >> hours;
cin >> minutes;
cin >> seconds;
}
void displayTime() const
{
cout << | hours; | ||
cout << minutes; | |||
cout << seconds; | |||
hours = | 12; | // | will not work |
minutes | = 35; | // | will not work |
seconds | = 40; | // | will not work |
}
};
In the above class function displayTime() has been declared as constant function , hence we will not be able to modify any of the data members of the class in function displyTime().
Mutable Data Type
If we wish to modify any data member in constant function, we can declare that data member as mutable as shown in the following example
class Time
{
int hours;
int minutes;
mutable int seconds;
public :
void readTime()
{
cin >> hours;
cin >> minutes;
cin >> seconds;
}
void displayTime() const
{
cout << | hours; | ||
cout << minutes; | |||
cout << seconds; | |||
hours = | 12; | // | will not work |
minutes | = 35; | // | will not work |
seconds | = 40; | // | will work |
}
};
As we have declared data member second in the class as mutable, we can modify it in even constant function.
Volatile Functions
A member function can also be declared as volatile. Volatile member function can only be invoked on volatile object.
A volatile object is a object whose values can be changed by external parameters such as hardware interrupt, network cards etc. which are not in control of the program.
Functions are powerful tools for creating modular design of program which is readable, effective , easy to modify, test, debug, and maintain……..
you can view video on Functions in C++ I |