What is "&"?
When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.
Modify the passed parameters in a function
If a function receives a reference to a variable, it can modify the value of the variable. For example, in the following program variables are swapped using references.
#include<iostream>
using namespace std;
void swap (int& first, int& second)
{
int temp = first;
first = second;
second = temp;
}
int main()
{
int a = 2, b = 3;
swap( a, b );
cout << a << " " << b;
return 0;
}
// Output: 3 2
Avoiding copy of large structures
Imagine a function that has to receive a large object. If we pass it without reference, a new copy of it is created which causes wastage of CPU time and memory. We can use references to avoid this.
In For Each Loops to modify all objects
We can use references in for each loops to modify all elements
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> vect{ 10, 20, 30, 40 };
// We can modify elements if we use reference
for (int &x : vect)
x = x + 5;
// Printing elements
for (int x : vect)
cout << x << " ";
return 0;
}