Callbyreference
Callbyreference
Callbyreference
Call by Reference
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 below function Swap(), which exchanges the values of the two
integer variables pointed to by its arguments.
Example:
#include<iostream>
main( )
int num1,num2;
cin>>num1>>num2;
Swap(num1,num2);
www.vectorindia.org 1
Call by Reference
int temp;
temp=a;
a=b;
b=temp;
Output:
10
20
before Swaping
num1 : 10 num2 : 20
after Swaping
num1 : 10 num2 : 20
one of the major disadvantages of pass by value is that all arguments passed by value
are copied into the function parameters. When the arguments are large structs or
classes, this can take a lot of time. References provide a way to avoid this penalty.
When an argument is passed by reference, a reference is created to the actual
argument (which takes minimal time) and no copying of values takes place. This allows
us to pass large structs and classes with a minimum performance penalty.
www.vectorindia.org 2
Call by Reference
References allow the function to change the value of the argument, which is undesirable
when we want an argument be read-only. If we know that a function should not change
the value of an argument, but don’t want to pass by value, the best solution is to pass
by const reference.
Example :
#include<iostream>
main()
int num=10;
Print(num);
x++; // compile time error : a const reference will not allow its value to be
changed
www.vectorindia.org 3
Call by Reference
Return by reference
Similar to pass by address, values returned by reference must be variables
(you should not return a reference to a literal or an expression that resolves
to a temporary value, as those will go out of scope at the end of the function
and you’ll end up returning a dangling reference). When a variable is
returned by reference, a reference to the variable is passed back to the
caller. The caller can then use this reference to continue modifying the
variable, which can be useful at times. Return by reference is also fast, which
can be useful when returning structs and classes.
However, just like return by address, you should not return local variables by
reference. Consider the following example :
int value=x*2;
www.vectorindia.org 4