Programming with Passion

Make the best out of everything.

Friday, 8 April 2016

What is meant by reference variable in C++?

What is meant by reference variable in C++?
In C++, reference variable allows you create an alias (second name) for an already existing variable. A reference variable can be used to access (read/write) the original data. That means, both the variable and reference variable are attached to same memory location. In effect, if you change the value of a variable using reference variable, both will get changed (because both are attached to same memory location).
How to create a reference variable in C++
Appending an ampersand (&) to the end of datatype makes a variable eligible to use as reference variable.
  1. int a = 20;
  2. int& b = a;
The first statement initializes a an integer variable a. Second statement creates an integer reference initialized to variable a
Take a look at the below example to see how reference variables work.
  1. int main ()
  2. {
  3. int a;
  4. int& b = a;
  5.  
  6. a = 10;
  7. cout << "Value of a : " << a << endl;
  8. cout << "Value of a reference (b) : " << b << endl;
  9.  
  10. b = 20;
  11. cout << "Value of a : " << a << endl;
  12. cout << "Value of a reference (b) : " << b << endl;
  13.  
  14. return 0;
  15. }
Above code creates following output.
Value of a : 10
Value of a reference (b) : 10
Value of a : 20
Value of a reference (b) : 20

No comments:

Post a Comment