Pass-by-reference is when you give someone a direct way to change something without needing to copy it first.
Imagine you have a toy box full of blocks. You give your friend the key to that same toy box, not a copy of it. Now, if your friend takes a block out or adds one in, you can see the change right away because it’s the same toy box.
Like sharing a snack
Think of it like sharing a bag of snacks with your best friend at school. You don’t give them a copy of the bag, you hand them the real one. If they take a few candies out, you can see it right away because it's the same bag.
Contrast with pass-by-value
If it were pass-by-value, like giving your friend a copy of the snack bag, then when they eat some snacks, you still have all yours, their copy doesn’t affect yours. But with pass-by-reference, it’s like sharing the real thing, what happens to one affects the other.
Examples
- You give your friend a pencil, but both of you still use the same pencil for drawing.
- When you pass by reference, changes made inside a function affect the original variable outside.
Ask a question
See also
- What are persistent data structures?
- What are recursive calls?
- What on Earth is Recursion? - Computerphile?
- What is recursion?
- AI Literacy: How do AI Image Generators Work?