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
๐น 3. Simple Example
๐น 4. Pass By Value vs Pass By Reference
Pass by Value
โ Original value not changed
Pass by Reference
โ Original value changed
๐น 5. Swap Two Numbers (Classic Example)
๐น 6. Pass By Reference with Arrays
โก Arrays are implicitly passed by reference.
๐น 7. Pass By Reference with Structures
๐น 8. const Reference (Read-Only Reference)
โ 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
โ Correct:
๐ Summary
Pass by reference modifies original variable
Use
&in function parametersFaster and memory-efficient
Use
const &when modification is not neededPreferred over pointers in many cases
