Pass by value (call by value) and Pass by reference (call by reference) :
Pass by value (call by value):
Pass by value (call by value):
- Original value is not modified in call by value.
- In call by value, value being passed to the function is locally stored by the function parameter in stack memory location.
- If you change the value of function parameter, it is changed for the current function only.
Example:
a=10
def f1(x):
print(x)
x=20
print(x)
f1(a)
print(a)
Output:
10
20
10
pass by reference (call by reference):
- In call by reference, original value is modified because we pass reference (address).
- Here, address of the value is passed in the function, so actual and formal arguments shares the same address space.
- value changed inside the function, is reflected inside as well as outside the function.
Example:
b=[1,2,3]
def f2(y):
print(y)
y[0]=10
y[1]=20
print(y)
f2(b)
print(b)
Output:
[1, 2, 3]
[10, 20, 3]
[10, 20, 3]
No comments:
Post a Comment