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::vector or std::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 Standard
void 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).