Unit 1
Reference
References in C++
• When a variable is declared as a reference, it becomes an
alternative name for an existing variable.
• A variable can be declared as a reference by putting ‘&’
in the declaration.
• Also, we can define a reference variable as a type of
variable that can act as a reference to another variable.
‘&’ is used for signifying the address of a variable or any
memory.
• Variables associated with reference variables can be
accessed either by its name or by the reference variable
associated with it.
Syntax
• data_type& ref = variable;
• Example:
int x = 10;
// ref is a reference to x.
int& ref = x;
Program to demonstrate
use of references
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
// Value of x is now changed to 20
ref = 20;
cout << "x = " << x << '\n';
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << '\n';
return 0;
}
Output:
x = 20 ref = 30
Return by reference
• reference is nothing but an alias(synonym) of
another variable.
• Syntax:
dataType& functionName(parameters);
where,
dataType is the return type of the function,
and parameters are the passed arguments to it.
C++ program to illustrate return
by reference
#include <iostream>
using namespace std;
// Global variable
int x;
// Function returns as a return by reference
int& retByRef()
{
return x;
}
int main()
{
// Function Call for return by reference
retByRef() = 10;
// Print X
cout << x;
return 0;
}
Output
• Output:
10
• Explanation:
Return type of the above function retByRef() is a
reference of the variable x so value 10 will be
assigned into the x.
Return by reference
#include <iostream>
using namespace std;
// Function to return as return by reference
int& returnValue(int& x)
{ // Print the address
cout << "x = " << x << " The address of x is " << &x << endl;
return x; // Return reference
}
int main()
{
int a = 20;
int& b = returnValue(a);
// Print a and its address
cout << "a = " << a << " The address of a is "<< &a << endl;
// Print b and its address
cout << "b = " << b << " The address of b is " << &b << endl;
// We can also change the value of 'a' by using the address returned by returnValue function
// Since the function returns an alias of x, which is itself an alias of a, we can update the value of a
returnValue(a) = 13;
cout << "a = " << a << " The address of a is "<< &a << endl;
return 0;
}
Output
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, variables are swapped using
references.
Program to demonstrate
Passing of references as parameters
#include <iostream>
using namespace std;
// Function having parameters as references
void swap(int& first, int& second)
{
int temp = first;
first = second;
second = temp;
}
int main()
{
int a = 2, b = 3;
// function called
swap(a, b);
// changes can be seen
// printing both variables
cout << a << " " << b;
return 0;