References in C++
If you want to create an alternate name for a variable, then this is option you have. You can access the variable as reference.
How to create a Reference?
It uses ‘&’
symbol to create the reference.
Syntax:
‘data_type &ref_name= variable;’
Eg:
‘int &ref = a;’
Let us create a C++ program to use the reference.
This program starts by including built-in header file
<iostream>.
- ‘main()’ function creates two variable ‘a’ and ‘reference’.
- Get the ‘a’ value from the user.
- Assign it to reference.
- Get the value two more time and assign it to reference.
- Print the value.
Program:
#include <iostream>
using namespace std;
int main() {
int a;
cout<<"Enter the value:"<<endl;
cin>>a;
//create the reference value and assign the variable
int &reference = a;
//let us change the value;
cout<<"The reference value
is:"<<reference<<endl;
cout<<"Enter another value to change reference
value:"<<endl;
cin>>a;
reference =a;
cout << "Now the value is = " <<
reference << '\n';
cout<<"Enter one more value to assign the
reference value:"<<endl;
cin>>a;
cout << "Now the reference has the value:"
<< reference << '\n';
return 0;
}
Output:
Enter the value:
23
The reference value is:23
Enter another value to change reference value:
56
Now the value is = 56
Enter one more value to assign the reference value:
78
Now the reference has the value:78
Applications of references:
It is useful for the following.
It avoids the copying object in a for loop.
It modifies the elements and passes the parameters.
Large structures can be easily reused.
Hope, this code is useful to you. This is the way of using
the reference variable in c++ program.
Comments
Post a Comment