Facebook Pixel

Pass by Value vs Pass by Reference Explained

A clear breakdown of how languages pass data to functions and why modifying a variable inside a function sometimes changes it globally.

The Most Confusing Concept for Beginners

When you pass a variable to a function and modify it inside, does the original variable change? The answer depends on whether the language uses Pass by Value or Pass by Reference.

Pass by Value

When you pass a primitive variable (like an integer), the computer creates a copy of that value and gives it to the function.

  • If you pass x = 10 to a function and the function changes x to 20, the original x outside the function remains 10. The function only modified its local copy.
  • This protects your original data from being accidentally altered.

Pass by Reference (or Object Reference)

When you pass a non-primitive variable (like an Array or an Object), the computer does not copy the entire array. It passes the memory address (reference) of the array.

  • If the function modifies the array, it goes to that memory address and changes the actual data.
  • The original array outside the function will reflect these changes.

Language Nuances

  • C++: You have explicit control. You can choose to pass by value (int x) or pass by reference using an ampersand (int &x).
  • Java: Java is strictly Pass by Value. However, for Objects, the value being passed is the reference to the memory. So modifying an array inside a function modifies the original, but reassigning the variable does not.

The Takeaway

Bugs related to unintentional data modification are notoriously hard to track down. Always know whether you are passing a copy of the data or a reference to the actual memory location.

Pass by Value means a copy of the variable's data is passed to the function. Modifications inside the function do not affect the original variable.

Pass by Reference means the memory address of the variable is passed. Modifications inside the function will alter the original variable's data.

Java is strictly pass-by-value. However, for objects/arrays, the 'value' passed is the memory reference, which allows the object's contents to be modified.

Because integers are primitives. Java passes a copy of the primitive value, so the original variable remains untouched.

In C++, you use the ampersand (&) operator in the parameter list (e.g., void modify(int &x)) to pass a variable by reference.

Please Login.
Please Login.
Please Login.
Please Login.