Reference Variable
Reference Variable
· A reference variable provides a pat name (alternative name) for a previously defined variable.
o Syntax:
§ data-type & reference-name = variable-name
o Example:
§ float total = 100;
§ float & sum = total;
· Reference variable and variable can be used interchangeably to represent that variable.
· As shown in above example sum and total can use interchangeably. In the memory, Both the variable refers to the same data object.
· Reference variable initialized at the time of declaration.
· Most of application of reference variables is in passing arguments to functions.
Explain call by reference.
Explain call by reference.
· Passing reference variable as an argument to the function is known as call by reference.
· In this, ‘formal’ arguments in the called function become ‘aliases’ to the ‘actual’ argument in the calling function.
· In this if any change it made with the function variable (alias) then it reflects to original variable (actual).
Example:
void swap (int & a, int & b) // a & b are ref variable
{
int t = a;
a = b;
a = b;
b = t;
}
Void main()
{
Int X, Y;
X = 10;
Y = 20;
Y = 20;
swap(X, Y);
cout << “\n X : “ << X;
cout << “\n X : “ << X;
cout << ”\n Y : “ << Y;
}
Output:
X : 20
Y : 10
Y : 10
· This function will exchange the value of m and n using their aliases (reference variable a and b).
Deference between call by value and call by reference.
Call by value
|
Call by reference.
|
In call by value mechanism we have to pass the variable as the argument to the function.
|
In call by reference mechanism we have to pass the reference of the variable as the argument to the function.
|
Syntax:
return-type function-name (data-type variable-name)
{ . . . . . //function body}
|
Syntax:
Return-type function-name (data-type & variable-name)
{ . . . . . //function body}
|
In call by value, if the value of the variable is change then it does not reflect to the original value of the variable.
|
In call by reference, if the value of the variable is change then it does reflect to the original value of the variable.
|
It creates the new set of variable for the function.
|
It does not create the new set of variable but the reference of the variable for the function.
|
Program occupies more memory if the call by value mechanism is used.
|
Program occupies less memory then the program uses the call by mechanism if the call by reference is used.
|