Pass-by-Value vs.
Pass-by-Reference
Understand how C++ passes arguments to functions: copies vs. aliases, and when to use each approach.
What is a Function Argument?
When you call a function, you provide arguments: the actual data values you pass in. The function receives those arguments through its parameters: the variable names declared in the function signature.
Pass-by-Value: Making a Copy
When a function parameter is declared without &, C++ creates an independent copy of the argument. Changes inside the function do not affect the original variable.
Pass-by-Reference: Sharing the Original
When a parameter is declared with &, the function receives a reference: an alias for the original variable. Changes inside the function directly modify the caller's data.
Why Does This Matter?
The Syntax Rule
Value vs. Reference: Side by Side
How to Decide Which to Use
Example 1: Pass-by-Value
The local copy n becomes 14.
The original x is untouched.
Example 2: Pass-by-Reference
n is an alias for x.
The original x was modified through the alias.
Example 3: Classic Swap Function
The const & Pattern
For large objects you want to read but not modify, use const &. This avoids the cost of copying while preventing accidental changes.
Returning Multiple Values
C++ functions can only return one value. Use reference parameters when a function needs to produce multiple outputs.
Common Mistakes
Comparison Summary
| Pass-by-Value | Pass-by-Reference | const & | |
|---|---|---|---|
| Syntax | int n | int& n | const int& n |
| Copy made? | Yes | No | No |
| Can modify original? | No | Yes | No |
| Accepts literals? | Yes | No | Yes |
| Best for | Small types | Modify / multi-return | Large read-only |
Question 1 of 5
What is printed by this code?
Question 2 of 5
Which parameter declaration allows a function to modify the original argument?
Question 3 of 5
What is printed by this code?
Question 4 of 5
Why is const & preferred over plain pass-by-value for a string parameter?
Question 5 of 5
What happens if you call func(10) where func is declared as void func(int& n)?