C++ References

πŸ”— C++ References

A reference in C++ is an alias (another name) for an existing variable.
It does not create a new variable, but refers to the same memory location.


1. Declaring a Reference

int x = 10;
int &ref = x;
  • ref is a reference to x

  • Both share the same memory


2. Reference Example

int x = 5;
int &r = x;
r = 10;

cout << x; // Output: 10

➑ Changing r also changes x.


Β 3. Reference vs Normal Variable

int a = 5;
int b = a;
b = 10;

cout << a; // 5

int a = 5;
int &b = a;
b = 10;

cout << a; // 10


4. References in Function Parameters (Very Important)

Without Reference (Call by Value)

void change(int x) {
x = 20;
}

❌ Original value not changed.


With Reference (Call by Reference)

void change(int &x) {
x = 20;
}

βœ” Original value is changed.


Example:

int a = 10;
change(a);
cout << a; // 20

5. Swap Two Numbers Using References

void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}

6. Reference Must Be Initialized

❌ Invalid:

int &r; // error

βœ” Valid:

int x = 10;
int &r = x;

Β 7. Reference Cannot Be Reassigned

int a = 10, b = 20;
int &r = a;
r = b; // copies value of b into a

➑ r still refers to a.


8. const Reference

int x = 10;
const int &r = x;
// r = 20; ❌ not allowed

βœ” Useful for read-only access
βœ” Prevents accidental modification


9. References with Arrays

int arr[3] = {1, 2, 3};

for (int &x : arr) {
x *= 2;
}


Β 10. Reference vs Pointer

ReferencePointer
Cannot be NULLCan be NULL
No reassignmentCan change address
Cleaner syntaxMore flexible
Must be initializedOptional initialization

πŸ“Œ Summary

  • Reference = alias of a variable

  • Must be initialized

  • Cannot be NULL or reassigned

  • Used heavily in functions and loops

  • Safer alternative to pointers in many cases

You may also like...