What is need of call by reference ? Explain with example.
Answers
The call by reference method of passing arguments to a function 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 passed argument.
To pass the value by reference, argument reference is passed to the functions just like any other value. So accordingly you need to declare the function parameters as reference types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments
eg.
// function definition to swap the values.
void swap(int &x, int &y) {
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
Call by reference is the process of passing the reference of of actual parameter to the formal parameters . Any change made in the formal parameters will affect the actual parameters .
Example â
class CB
{
int a ;
CB ()
{
a = 10 ;
}
static void change ( CB ref )
{
ref .a += 2 ;
}
static void main ()
{
CB obj = new CB () ;
System.out.println (" Before change " +obj.a) ;
change(obj);
System.out.println (" After change "+obj.a );
}
}
=> Therefore , here before swap 10 will be given as output and after swap 12 will be given as output due to call by reference change has been reflected on the actual parameter .