Skip to content
UniCircle
MediumConceptualParameter passing

Pass by value vs pass by reference in C, C++, Java and Python

Question PROG-PAR-005

A function tries to swap two variables passed to it. Explain why this works or fails in C, C++, Java and Python. Is Java pass-by-reference for objects?

Show the explanation

Definitions

  • Pass by value: the function receives a copy. Assigning to the parameter does not affect the caller's variable.
  • Pass by reference: the parameter is an alias for the caller's variable. Assigning to it changes the caller's variable.

C: always by value. To let a function change the caller's variables, you pass their addresses (still passed by value) and dereference them:

C
void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
swap(&x, &y);              /* works */

C++: both. void swap(int &a, int &b) uses real references, and swap(x, y) works. std::swap does the same.

Java: always by value, including for objects. For an object, the value that gets copied is the reference (a pointer to the object). So:

  • You can change the object's state: list.add(5) or p.age = 30 is visible to the caller.
  • You cannot make the caller's variable point to a different object. obj = new Thing() inside the method only changes the local copy. A swap(Integer a, Integer b) method therefore has no effect on the caller.
  • Answer: "Java is pass-by-value; for objects the value is a reference." Saying "objects are passed by reference" is the classic wrong answer.

Python: "pass by object reference" (also called call by sharing). Arguments are names bound to the same objects as the caller's names.

  • Mutating a mutable object (lst.append(1)) is visible to the caller.
  • Rebinding the parameter (lst = [9], x = x + 1) is not.
  • Immutable objects (int, str, tuple) can only be "changed" by rebinding, so the caller never sees the change.
  • The idiomatic swap is x, y = y, x at the call site, or a function that returns the new values.

Interview summary: a swap function works in C only through pointers, in C++ through references, and in Java and Python not at all for the caller's variables. What does work in all of them is changing a shared mutable object.

Original UniCircle question. Last reviewed 22 Oct 2026.