If you like my posts please leave a comment.

Thursday, October 11, 2012

Calling a Function by Reference



In my previous post you have seen that, in call by value method, the called function creates a new set of variables and copies the values of arguments into them. The function doesn’t have any access to the original variable i.e. actual parameter; can work with the copies of the values it created. This method is useful when you want that original values should not be modified. Call by value method assures that value of the actual parameters will not be modified.
            The call by reference method uses a different mechanism. In this method in place of passing the 
value of an actual parameter (predefined local variable) to the function being called (its own function definition), a reference to the address of the actual parameter is assigned to the receiving function’s parameter. In this way the receiving parameter (formal argument) becomes an Alias (i.e. different name) for a predefined variable. That is the same variable’s value can be accessed by any of these two names.
            Unlike passing by value, passing by address or calling by reference gives us the ability to change a variable in the receiving function and keep the change in effect in the calling function as well. Let’s try to understand this concept more with help of a program and its output.


/*Program to swap the values of two variables to illustrate the concept of calling a funciton by reference*/
#include <iostream.h>
#include <conio.h>
void swap(int &, int &); //Function prototype
void swap(int &x, int &y)//Function definition starts
{
     int temp;
     cout<<"\n\n--------------------------------------------\n";
     cout<<"\n\n Let's Check...\n";
     cout<<"\n\n Address of x = "<<&x<<" so the value = "<<x;
     cout<<"\n\n Address of y = "<<&y<<" so the value = "<<y;
     cout<<"\n\n Address of temp = "<<&temp;
     cout<<"\n\n--------------------------------------------\n";
     cout<<"\n\n Now swaping begins...\n";
     temp = x; cout<<"\n"<<&temp<<" <-  "<<x<<" <-"<<&x;
     x = y; cout<<"\n"<<&x<<" <- "<<y<<" <- "<<&y;
     y = temp; cout<<"\n"<<&y<<" <-  "<<temp<<" <- "<<&temp;
     cout<<"\n\n--------------------------------------------\n";
     cout<<"\n\n Now the swaped values....";
     cout<<"\n\n Address of x = "<<&x<<" and the value = "<<x;
     cout<<"\n\n Address of y = "<<&y<<" and the value = "<<y;
     cout<<"\n\n--------------------------------------------\n";

}
void main()
{
clrscr();
int A = 5, B = 10;
cout<<"\nAddress of A = "<<&A<<" and the value = "<<A;
cout<<"\nAddress of B = "<<&B<<" and the value = "<<B;
swap(A,B);
cout<<"\n\nAfter the swap() function is called\, values of variables in main()";
cout<<"\n\nAddress of A = "<<&A<<" and the value = "<<A;
cout<<"\nAddress of B = "<<&B<<" and the value = "<<B;
getch();
}
Output:

 

No comments:

Post a Comment