Skip to content

Pass-by-value and Pass-by-reference

February 24, 2023 | 12:46 AM

In programming, variables can be passed to functions or methods in two ways: pass-by-value and pass-by-reference. These two methods are fundamental to programming and are used in different programming languages. Understanding the difference between the two is important for writing efficient and effective code.

Pass-by-value

When a variable is passed by value, a copy of the variable is made and passed to the function. The function then operates on the copy of the variable, leaving the original variable unchanged. Any changes made to the variable within the function will not affect the original variable. Pass-by-value is used in languages such as C, C++, Java, and Python (for primitive data types).

Here’s an example of pass-by-value in Python:

def square(num):
    num = num ** 2
    return num

x = 5
print(square(x))   # output: 25
print(x)           # output: 5

In the above example, the variable x is passed to the square function as a parameter. However, since Python uses pass-by-value, the function creates a copy of x called num and squares it. The original variable x remains unchanged.

Pass-by-reference

When a variable is passed by reference, a reference to the original variable is passed to the function. The function operates on the original variable, and any changes made to the variable within the function will affect the original variable. Pass-by-reference is used in languages such as C++ (using pointers) and Python (for non-primitive data types).

Here’s an example of pass-by-reference in Python:

def add_to_list(item, lst):
    lst.append(item)
    return lst

my_list = [1, 2, 3]
print(add_to_list(4, my_list))   # output: [1, 2, 3, 4]
print(my_list)                   # output: [1, 2, 3, 4]

In the above example, the add_to_list function takes in two parameters: item and lst. lst is a reference to the original list my_list. Since Python uses pass-by-reference for non-primitive data types, any changes made to lst within the function will affect the original my_list variable. Therefore, when the function appends the item to the lst, the original my_list variable is also updated.

In conclusion, pass-by-value and pass-by-reference are two methods of passing variables to functions in programming. Pass-by-value creates a copy of the variable, while pass-by-reference passes a reference to the original variable. Understanding the difference between the two is important for writing efficient and effective code.