References in C++

  • October 18, 2022
  • C++
Accessing Elements

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.

Pointers vs. References:

References and pointers are frequently confused, but there are three major differences between the two.

  • NULL references are not permitted. You must always be able to assume that a reference refers to a valid piece of storage.
  • Once a reference is set to an object, it cannot be changed to another object. At any time, pointers can be directed to another object.
  • When a reference is created, it must be initialized. At any time, pointers can be initialized.
Functions with references:

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.

Example:
#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;
}
Output:
Before swapping: 2 3
After swapping: 3 2
Const Reference:

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);
}
Output:
/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:

  • References are less powerful than pointers
  • References are safer and easier to use

Note: also read about Mutable keyword in C++

Follow Me

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

Leave a Reply

Your email address will not be published. Required fields are marked *