How do I pass a variable by reference?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In most programming languages, passing a variable by reference means that a function receives a reference to the original variable rather than a copy. This allows the function to modify the original variable directly.
Here’s how this is handled in different languages, including Python, C++, Java, and JavaScript:
1. Python
In Python, all variables are references to objects, but the behavior depends on whether the object is mutable or immutable.
Mutable Objects (Lists, Dictionaries, etc.)
Mutable objects can be modified within a function.
- The function modifies the original
numberslist because lists are mutable.
Immutable Objects (Integers, Strings, etc.)
For immutable objects, reassignment does not affect the original variable.
Simulating Pass-by-Reference with Containers
To pass an immutable value "by reference," wrap it in a mutable container like a list or dictionary:
2. C++
In C++, you can explicitly pass variables by reference using the & operator in the function signature.
Example:
Here:
int &xmeansxis a reference to the original variable.
3. Java
Java uses pass-by-value for primitive types and pass-by-reference-value for objects. You cannot directly pass a variable by reference, but you can modify object properties.
Example:
- Objects are passed by "reference value," so you can modify their internal state.
4. JavaScript
JavaScript is pass-by-value for primitives and pass-by-reference-like for objects.
For Objects:
You can modify the properties of an object passed to a function.
For Primitives:
Primitives (e.g., numbers, strings) are passed by value, so they cannot be modified directly.
Summary Table
| Language | Pass-by-Reference Support | Example |
| Python | No explicit pass-by-reference | Use mutable objects or containers like lists. |
| C++ | Yes, with & operator | void modify(int &x) { x += 10; } |
| Java | No explicit pass-by-reference | Use objects to modify internal properties. |
| JavaScript | Objects are reference-like | Modify object properties, but primitives stay unmodified. |
Key Takeaway
- In Python and JavaScript, use mutable objects (lists, dictionaries, or objects) to simulate pass-by-reference behavior.
- In C++, use the
&operator for true pass-by-reference. - In Java, pass an object and modify its properties since primitive types are pass-by-value.
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.