Skip to content
BENIBIX Learn

Pass by Reference

Development🧩 Programming ConceptsFunctions

Also known as Call by Reference, Passing by Reference

The function gets a link to the real value. So its changes show outside too.

Think of it like

It is like giving a friend your house key. Whatever they move inside, you will find moved.

Example

A score of 5 is passed by reference to a function that adds 1. Back outside, the score now reads 6.

Why it matters

It lets a function update big data without copying it. It is also a common source of surprise changes.

Definition

Pass by reference means a function gets a link to the caller's own variable, not a copy. If the function changes it, the caller sees the change. C++ does this when a parameter is marked with &. It avoids copying big data. But a function can now change things the caller did not expect.

Example code

cpp
void addOne(int& n) { n = n + 1; }

int score = 5;
addOne(score);
// score is now 6
The & makes n a link to score. Changing n changes score.
On the right, the function reaches the real value. So it now reads 6.

Common mistake

Thinking all languages work this way. Python and Java do not. A function there can change an object you pass, but it cannot swap your variable for a new one.

Key takeaways

  1. 1
    A link goes in. The function reaches the original.
  2. 2
    Changes show. The caller sees every edit.
  3. 3
    No copy. Fast, even for big data.

Compare

Learn it properly