Core Module
12 min forge
C++ Pass by Value vs Reference
Understanding how data is passed to functions and its impact on performance and persistence.
C++ Pass by Value vs Reference
π What is it
When passing arguments to functions, you can either pass a copy of the data (Pass by Value) or pass the memory address of the original data (Pass by Reference).
β‘ When to use
- Pass by Value: For small types like
int,char, or when you don't want the function to modify the original value. - Pass by Reference: For large objects (like
std::vectororstd::string) to avoid expensive copying, and when you NEED the function to modify the original value.
π§ Time complexity
- Pass by Value: $O(N)$ for copying an object of size $N$.
- Pass by Reference: $O(1)$ (only the address is passed).
π» Code example
cpp Standardvoid modifyValue(int x) { x = 100; } // Copy void modifyRef(int &x) { x = 100; } // Reference int main() { int a = 5, b = 5; modifyValue(a); // a is still 5 modifyRef(b); // b is now 100 }
β Common mistakes
- Passing large objects by value in performance-critical loops.
- Modifying a reference when you intended to only read from it (use
const &to prevent this). - Returning a reference to a local variable (Dangling reference).