3. Write a cpp program which explain the use of reference variable.
In C++, a reference is a way to refer to a specific object or value using an alias, rather than creating a new copy of the object or value. A reference is created using the & operator, and is accessed using the same syntax as a regular variable.
Here's an example of how you can use a reference variable in C++:
#include <iostream>
using namespace std;
void main()
{
int x = 10;
int &y = x; // y is a reference to x
cout << x << endl; // prints 10
cout << y << endl; // prints 10
y = 20; // updates the value of x to 20
cout << x << endl; // prints 20
cout << y << endl; // prints 20
return 0;
}
Output
10
10
20
20
In this example, we create a reference y to the integer variable x. We can use y to access the value of x, and any updates to y will be reflected in the value of x.
References are often used as function arguments to avoid copying large objects or values. They can also be used to pass objects or values by reference, rather than by value.
Here's an example of how you can use a reference as a function argument:
#include <iostream>
using namespace std;
void increment(int &x) // x is a reference to an integer
{
x++; // increments the value of x
}
void main()
{
int x = 10;
increment(x); // increments the value of x
cout << x << endl; // prints 11
return 0;
}
Output
11
In this example, we pass the integer variable x to the increment function by reference.
This allows us to update the value of x directly within the function, rather than creating a new copy of x.