Reference variables in C++
A reference variable in C++ is an alias for another variable.
Such a variable looks like an
ordinary variable but behaves like a pointer. It always refers to another variable.
In function calls, reference parameter modifies the actual argument, without the hassle of addresses and indirections.
Defining a reference variable
A reference variable is defined with & along with its name. It should always be initialized during definition.
int &b = a;/*definition of a reference*/
b is a reference variable and
it refers to a. That is b is another name for a.
Functions with reference parameters
A function with reference parameter changes the actual argument because the parameter is an alias for argument. In case of large structs and classes, it is better to send a reference parameter, as it avoids copying of data.void triple(int &a) { a *=3; } int main() { int m = 10; triple(m);/*changes m to 30*/ cout<<m; }
In the above example, m is sent as a reference parameter. So m is changed by the function triple().
If the function needs a reference parameter for efficiency, but the function should not change the argument, you should define parameter as constant reference.
Notes
- A reference should always be initialized to another variable while defining it.
- A reference variable can not refer to a different variable later.
- i.e. b = c ;
- will not make b refer to c. Instead it assigns c to a.
- A reference variable should always be initialized when defining.
- float &m1 = m2; /*m1 is initialized to m2*/
- An array of reference variables is not possible
- If a function has a reference parameter, changes to this reference parameter will change the actual argument.
- If a function returns a reference value, that function can be used in LHS of an assignment statement.
Returning a reference
A function returning a reference has the advantage that it can be used in LHS of an expression. But you have to make sure that, the return value of such a function is within the scope even when function exits.
int &fn1(int m,int n) { if(m>n) return m; return n; } int main() { int a1 = 3,b1=12; fn1(a1,b1) = 100; }
Here main fn1() returns a reference to b1. So b1 will be set to 100 in the assignment statement of main().
Comments
Post a Comment