Intermediate Topic 26 of 54 Programming Fundamentals
Pass by Value vs Reference
Whether a function receives a copy of data or a handle to the original.
How it works
Pass by value gives the function a copy of the argument, so changes inside do not affect the caller; pass by reference gives the function access to the original variable. Many languages, including Java and Python, pass references to objects by value: reassigning the parameter does not affect the caller, but mutating the object it points to does. Understanding this distinction explains many surprises.
Step-by-step walkthrough
- With pass by value the function gets its own copy.
- Changing the copy leaves the caller's variable alone.
- With a reference both names point to the same object.
- The function mutates the shared object.
- The caller sees the change because it is the same object.
Where it is used
Deciding whether a function can change its inputs, such as sorting a list in place, avoiding costly copies of large structures by passing references and designing APIs with clear ownership all depend on this idea.
Common pitfall
Unexpected mutation of a caller's data is the main hazard, as is assuming a copy was made when it was not. Copy defensively when needed, document whether a function mutates its arguments, and prefer immutable data where possible.
Where it fits in the course
Pass by Value vs Reference is topic 26 of 54 in Programming Fundamentals, rated Intermediate. It follows Call Stack. The next topic is Mutability.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Pass by Value vs Reference?
Where do people use Pass by Value vs Reference?
What is the most common mistake with Pass by Value vs Reference?
What should I learn before this topic?
How can I practice it?
Is Pass by Value vs Reference hard to learn?
How long does it take to learn Pass by Value vs Reference?
Which topics are related to Pass by Value vs Reference?
What should I study after Pass by Value vs Reference?
Related topics
- Call Stack (Programming Fundamentals)
- Mutability (Programming Fundamentals)
- Base Case (Programming Fundamentals)
- Error Handling (Programming Fundamentals)
- Expected Value (Math for Computing)
- Singular Value Decomposition (Math for Computing)
- Key-Value Stores (Databases)