C++ Functions Pass By Reference

๐Ÿ” C++ Functions โ€“ Pass By Reference

Pass by reference allows a function to work on the original variable, not on a copy.
Any change made inside the function directly affects the callerโ€™s variable.


๐Ÿ”น 1. Why Pass By Reference?

  • Avoid copying data (faster)

  • Modify original values

  • Useful for large objects (arrays, structures, classes)


๐Ÿ”น 2. Basic Syntax

void functionName(dataType &parameter) {
// modify parameter
}

๐Ÿ”น 3. Simple Example

void change(int &x) {
x = 50;
}
int a = 10;
change(a);

cout << a; // Output: 50


๐Ÿ”น 4. Pass By Value vs Pass By Reference

Pass by Value

void update(int x) {
x = 100;
}

โŒ Original value not changed


Pass by Reference

void update(int &x) {
x = 100;
}

โœ” Original value changed


๐Ÿ”น 5. Swap Two Numbers (Classic Example)

void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int x = 5, y = 10;
swap(x, y);


๐Ÿ”น 6. Pass By Reference with Arrays

void modify(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}

โžก Arrays are implicitly passed by reference.


๐Ÿ”น 7. Pass By Reference with Structures

struct Student {
int marks;
};
void update(Student &s) {
s.marks = 90;
}


๐Ÿ”น 8. const Reference (Read-Only Reference)

void show(const int &x) {
cout << x;
}

โœ” Prevents modification
โœ” Efficient for large objects


๐Ÿ”น 9. Pass By Reference vs Pointer

Reference Pointer
Cleaner syntax More flexible
Cannot be NULL Can be NULL
No dereferencing Needs *
Safer Error-prone

โŒ Common Mistakes

void fun(int &x) {
// ok
}
fun(10); // โŒ cannot pass literal

โœ” Correct:

int a = 10;
fun(a);

๐Ÿ“Œ Summary

  • Pass by reference modifies original variable

  • Use & in function parameters

  • Faster and memory-efficient

  • Use const & when modification is not needed

  • Preferred over pointers in many cases

You may also like...