Functions (Pass by Reference and Value)
EasyCopies versus aliases
Problem
A function packages reusable logic. Pass-by-value copies the argument (changes stay local); pass-by-reference (& in C++) shares the original, so the function can modify the caller's variable.
Give a copy (changes stay inside) or share the original (changes stick).
The idea
Passing by value hands the function a copy, so changes inside are invisible outside. Passing by reference hands it an alias to the caller's own variable, so changes stick — and it avoids copying a large array, which is why big containers are almost always passed by reference.
The trick
- Pass small values (int, char, bool) by value; pass containers by reference.
- `const T&` gives you the no-copy speed of a reference with a compiler-enforced promise not to modify it.
- In Java and Python everything is passed by value, but for objects that value is a reference — so mutating the object is visible to the caller while reassigning the parameter is not.
Step 1 of 4. One variable holds 5. We will hand it to two functions that both try to set it to 10. Values: 5, 5. caller 5.
1void byValue(int x) { x = 10; } // caller unchanged2void byRef(int &x) { x = 10; } // caller's value changes3int a = 5; byRef(a); // a is now 10Input
- array
- [5, 5]
Memory
- caller
- 5
- copy
- —
Check yourself
2 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- x = 5; addOne(x) taking int n
- Output:
- x is still 5
- Explanation:
- n is a copy. Changing it changes the copy, and the original never hears about it.
Example 2
- Input:
- x = 5; addOne(x) taking int& n
- Output:
- x is now 6
- Explanation:
- n is another name for x, so the change sticks. This is why passing a large array by reference is both faster and riskier.
Finished the walkthrough? Add it to your streak.