c++References
c++References
Types of references
1.Lvalue
Refers to a named variable. It’s declared using the & operator. It behaves syntactically .
Example:
#include <iostream>
Int temp = x;
X=y;
Y=temp;
Int main()
Int a{ 10 },b{ 20 };
swap(a, b);
Return 0;
OUTPUT
a = 10, b = 20
a = 20, b = 10
2. Rvalue
Refers to a temporary object. Its declared using the && operator. Are commonly used in move
semantics and perfect forwarding They can be universal reference, which can bind both R-values
and l-value.
Example:
#include<iostream>
using namespace std;
//Declaring rvalue references to the
//rvalue passed as the parameter
Void printReferenceValue(int&& x)
{
Cout << x << endl;
}
//Driver Code
Int main()
{
//Given value a
Int a{ 10 };
OUTPUT
100
3.const references
Are references that provide read only access to the referred object.
Are often used as a function parameter to avoid making unnecessary copies and to express the
intention of not modifying the past object.
Example:
#include<iostream>
using namespace std;
Void my_function(const int& value) {
cout<< “The value is ” << value << endl;
}
Int main(){
Int x=42;
my_function(x);
return 0;
}
OUTPUT
42
Applications of references
1.Modifying passed parameters:
References are often used in function parameter passing to avoid unnecessary object copying.
When a function receives a reference to an object as a parameter, it can directly access and
modify the original object rather than creating a copy.
Example:
#include < iostream>
using namespace std;
int main() {
int a = 5;
increment(a);
cout<< a <<endl;
}
OUTPUT
6
OUTPUT
Processing vector with size: 5
3.Range-based loops:
References are often used in range-based loops to directly access and modify elements of a
container.
Example:
#include <iostream>
using namespace std;
int main(){
void modifyData(int&data){
data *=2;
}
int main(){
int sharedData=10;
cout<< “Before modification:
sharedData =”<< sharedData<<endl;
modifyData(sharedData);
cout<< “After modification:sharedData = ””<<sharedData<<endl;
return 0;
}
OUTPUT
Before Modification =10
After Modification = 20