Pass by Value vs Pass by Reference in C++: Key Differences and Usage
pass by value means copying the actual data to the function, so changes inside don't affect the original. Pass by reference passes the actual variable itself, allowing the function to modify the original data directly.Quick Comparison
Here is a quick side-by-side comparison of pass by value and pass by reference in C++.
| Factor | Pass by Value | Pass by Reference |
|---|---|---|
| Data Handling | Copies the value to the function parameter | Uses the original variable's memory address |
| Effect on Original | Original variable remains unchanged | Original variable can be modified |
| Performance | Slower for large data due to copying | Faster as no copying occurs |
| Syntax | Function parameter is normal variable type | Function parameter uses & symbol (reference) |
| Use Case | When original data should stay safe | When function needs to modify original data or avoid copying |
Key Differences
Pass by value means the function receives a copy of the argument's value. Any changes made inside the function affect only the copy, leaving the original variable unchanged. This is simple and safe but can be inefficient for large data types because copying takes time and memory.
Pass by reference means the function receives a reference (alias) to the original variable. Changes inside the function directly affect the original variable. This avoids copying, improving performance, especially for large objects, but requires care to avoid unintended side effects.
In C++, you declare pass by reference by adding an ampersand & after the parameter type. This tells the compiler to use the original variable's address instead of making a copy.
Pass by Value Code Example
This example shows how pass by value works. The function tries to change the number, but the original stays the same.
#include <iostream> void changeValue(int x) { x = 100; // changes local copy only } int main() { int num = 50; changeValue(num); std::cout << "num after changeValue: " << num << std::endl; return 0; }
Pass by Reference Equivalent
This example shows pass by reference. The function changes the original variable directly.
#include <iostream> void changeValue(int &x) { x = 100; // changes original variable } int main() { int num = 50; changeValue(num); std::cout << "num after changeValue: " << num << std::endl; return 0; }
When to Use Which
Choose pass by value when you want to protect the original data from changes and the data size is small, like basic numbers or small structs. It keeps your code safe and simple.
Choose pass by reference when you want the function to modify the original data or when passing large objects to avoid the cost of copying. This improves performance but requires careful handling to avoid bugs.