DEV Community

Cover image for Passing Argument By Object Reference
datatoinfinity
datatoinfinity

Posted on

Passing Argument By Object Reference

Passing argument by object reference, you will not understand in coding level it more of memory thing how memory work for passing an argument I will give you two example from python and C.

Python (Object Reference)

def change_box(box):
    box["item"] = "new toy"  

my_box = {"item": "old toy"}  
print("Before:", my_box)  # Output: {'item': 'old toy'}
change_box(my_box)  # Pass the reference to the box
print("After:", my_box)  # Output: {'item': 'new toy'}
Before: {'item': 'old toy'}
After: {'item': 'new toy'}
  1. Creating my_box:
  • Python creates a dictionary {"item": "old toy"} at some memory address, say 0x1234.
  • my_box is a variable that holds the reference 0x1234 (the address of the dictionary).
  1. Calling change_box(my_box):
  • The function change_box gets a copy of the reference 0x1234, stored in its parameter box.
  • Now, both my_box (outside) and box (inside the function) point to the same dictionary at 0x1234.

3.Modifying the Object:

  • When box["item"] = "new toy" runs, it modifies the dictionary at 0x1234.
  • Since my_box still points to 0x1234, it sees the change ({"item": "new toy"}).
  1. What If We Reassign? (Uncomment the line):
  • If you uncomment box = {"item": "another box"}, Python creates a new dictionary at a different address, say 0x5678.
  • Now, box points to 0x5678, but my_box still points to 0x1234. The original dictionary (my_box) remains unchanged.

C (Pass by Value)

#include 

void try_to_change(int x) {
    x = 100;  
}

int main() {
    int num = 10;
    try_to_change(num);
    printf("num = %d\n", num);  
    return 0;
}
num = 10

num is stored at some memory address, say 0x1000, with value 10. The function try_to_change gets a copy of num’s value (x = 10) stored at a different address, say 0x2000. Changing x only affects 0x2000, not 0x1000.

  • Passing by Reference Using Pointers
#include 

void change_number(int *ptr) {
    *ptr = 100;  
}

int main() {
    int num = 10;
    printf("Before: num = %d\n", num);  
    change_number(&num);  // Pass the address of num
    printf("After: num = %d\n", num);   
    return 0;
}
Before: num = 10
After: num = 100

I know this topic is complicated, not easy to understand. But please do let me know which part you don't understand. This is easiest way to understand.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.