C++ references allow you to give a variable a second name that you can use to read or modify the original data stored in that variable. Once a reference has been initialized with a variable, it can be referred to using either the variable name or the reference name. For instance,
int x=19;
int &a=x; //here a is a reference to int x.
A variable can be declared as a reference by including ‘&’ in the declaration, and there is no need to use the ‘*’ to dereference a reference variable.
References and pointers are frequently confused, but there are three major differences between the two.
When a function receives a variable reference, it can change the variable’s value.
Note: When we return a reference from a function, whatever the reference is connected to should not be out of scope when the function ends. Make that global or static.
#include <iostream>
using namespace std;
void swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
int main()
{
int a = 2, b = 3;
cout <<"Before swapping: "<< a << " " << b;
swap(a, b);
cout<<"After swapping: " << a << " " << b;
return 0;
}
Before swapping: 2 3
After swapping: 3 2
Consider a function that must accept a large object. If we pass it without a reference, a new copy is created, wasting CPU time and memory. To avoid this, we can use const references. For instance,
void func(const int& x)
{
x++;
} // ERROR
int main()
{
int i=10;
func(i);
}
/tmp/RXDruFSvQc.cpp: In function 'void func(const int&)':
/tmp/RXDruFSvQc.cpp:3:5: error: increment of read-only reference 'x'
3 | x++;
| ^
Because the argument is passed as a const reference, we cannot change it in the function.
Note:
Note: also read about Mutable keyword in C++
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…