In the previous post I had talked about main functions and function prototyping. In this post I would like to continue on functions and cover all the areas around them.
Call By Reference
Limitations of Call by Value
In C language a function call passes arguments by value. The Called function creates a new set of variables and copies the values of arguments into them. The function does not have access to the actual variables in the calling program and can only work on the copies of the actual values. This mechanism works fine until the function does not need to alter the values of the original variables in the calling program.
But such demanding situations might arise where we need to change the values of the variables in a calling function. Such as in the case of Bubble sort problem where we need to compare two adjacent elements in the list and interchange their values according the the comparison results if needed. If a function is used for creating a Bubble sort algorithm then it should have the capability to alter the values of variables in the calling functions, which is not possible by call by value method.
Call By Reference
In C++ we use reference variables which enable us to pass parameters to the functions by reference. When we pass an argument by reference, the formal arguments in the called function becomes aliases to the actual arguments in the calling functions. This means that when the function is working with its own arguments it is actually working on the original data.
An example would make things appear easier,
void swap ( int &a , int &b ) //a and b are reference variables
{
int t = a;
a=b;
b=t;
}
Now if m and n are two integer variables, then the function call
swap (m,n);
will exchange the values of m and n using the aliases a and b.
In C languages this is accomplished by using pointers and indirections.
Return By Reference
A function can also return a reference. Consider the following function :
int & max (int &a, int &b)
{
if (a>b)
return a;
else
return b;
}
Since the return type of max() is int&, the function returns references to a or b. Then a function call such as max (x,y) would yield a reference to either x or y depending on their values. This means that this function call can appear on the left hand side of an assignment statement. That is, the statement
max (x,y) = -1;
is legal and assigns -1 to x if it is larger otherwise -1 is assigned to y.
In the next post I would stress on inline functions, default arguments and function overloading.
No comments:
Post a Comment
Thank you for commenting.