Topic 31 of 83
Pass by Reference
Overview
Pass by value copies the argument. Pass by reference passes the actual memory address, allowing the function to modify the original variable and avoiding expensive copying.
Syntax
cpp
// Pass by Value (Copies)
void modifyValue(int x) { x = 99; }
// Pass by Reference (Modifies original)
void modifyRef(int& x) { x = 99; }
// Pass by Const Reference (Read-only, no copy overhead)
void printBigObject(const std::string& str) { cout << str; }Common Pitfalls
- Forgetting the ampersand `&` and accidentally passing a massive vector by value, causing huge slowdowns.
Interview Tips
- Always pass large objects (like std::string or std::vector) by `const reference` (const std::string&) to prevent massive performance drops from copying data.
Real-World Example
A swap function requiring pass-by-reference.
example
cpp
#include <iostream>
using namespace std;
void swapVals(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 20;
swapVals(x, y);
cout << "x: " << x << " y: " << y << endl; // Prints x: 20 y: 10
return 0;
}