C++ References

In C++, when we declare a variable as a reference it will become an alias of the existing variable. We can declare a variable as a reference using "&" in the declaration.

Example :

#include<iostream> 
using namespace std; 
  
int main() 
{ 
  int A = 10; 
  
  // refer is a reference to A. 
  int& refer = A; 
  
  // Value of A is now changed to 20 
  refer = 20; 
  cout << "A = " << A << endl ; 
  
  // Value of A is now changed to 30 
  A = 30; 
  cout << "refer = " << refer << endl ; 
  
  return 0; 
} 

Output:

A = 20
refer = 30 


In the above example, A is a variable of type int and then we create reference variable of A, which is refer. So when we change the value of A, the value of the reference variable will also change.

Difference Between Pointer and Reference

Pointer Reference
The pointer variable can refer to NULL. The reference variable can never refer to NULL.
An uninitialized pointer can be created. An uninitialized reference can never be created.
*, -> is used & is used
The pointer is the memory address of a variable. The reference is an alias for a variable.

Exercise:-

1. Which of the following statement is correct?

A. A reference is stored on heap.
B. A reference is stored on stack.
C. A reference is stored in a queue.
D. A reference is stored in a binary tree.

View Answer


2. Which of the following statement is correct about the references?

A. A reference must always be initialized within functions.
B. A reference must always be initialized outside all functions.
C. A reference must always be initialized.
D. Both A and C.

View Answer



Program

C++ program to Reference to print value of student_age

#include <iostream>
int main()
{
	int student_age=10;
	int &age=student_age;	// reference variable

	cout<< " value of student_age :"<< student_age << endl;
	cout<< " value of age :"<< age << endl;

	age=age+10;
	cout<<"\nAFTER ADDING 10 INTO REFERENCE VARIABLE \n";
	cout<< " value of student_age :"<< student_age << endl;
	cout<< " value of age :"<< age << endl;
	return 0;
}


Output:
value of student_age :10
value of age :10

AFTER ADDING 10 INTO REFERENCE VARIABLE
value of student_age :20
value of age :20  



Visit :


Discussion


* You must be logged in to add comment.