What is pass-by-reference?

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.

Take the quiz →

Examples

  1. Imagine you have a backpack, and when you pass it to your friend, they can add or remove items, the same backpack is being used.
  2. You give your friend a pencil, but both of you still use the same pencil for drawing.
  3. When you pass by reference, changes made inside a function affect the original variable outside.

Ask a question

See also

Discussion

Recent activity