Presented by:
[Amanullah Khan, Shahzada khan, Haris]
A reference in C++ is an alternative name (alias) for an existing variable.
It does not create a new copy of the variable — it simply gives another
name to the same memory location.
Declared using the & (ampersand) symbol.
Why Do We Use References? (Use Cases)
1. Function Arguments (Pass by Reference)
Helps functions modify the original variable.
Avoids copying large data (faster).
2. Returning Multiple Values
Functions can return more than one value using references.
3. Improving Performance
Useful when passing large objects (e.g.,
arrays, strings, classes).
Saves memory and increases speed.
4. For Range-based Loops
Used in for(int &x : array) to modify elements
directly.
Benefits Of Using Reference:
No Copying: Efficient memory usage.
Direct Access: Works on the actual variable.
Easy Syntax: Simpler and cleaner than pointers.
Faster Programs: Avoids extra memory and processing.
Safe: Must be initialized, cannot be NULL (unlike pointers).
PROGRAM EXAMPLE
#include<iostream>
using namespace std;
int main(){
int a = 10;
int &ref = a;
ref = 25;
cout<<"a = "<<a;
}
Output:
a = 25