Sunday, October 5, 2008

By Value Vs By Reference

Types of arguments in procedures

1. ByVal
2. ByRef


ByVal:

Indicates that the argument is passed by value.

ByRef :
Indicates that the argument is passed by reference.

By default all arguments are 'ByRef'.

Syntax -

Function demo_add(a,b)

demo_add=a+b

End Function

Here a,b are the arguments. By default these are 'ByRef'.

In simple words ByRef Means the value which is assigned to the variable with in the function is permanent and we can use that value out side of that function also.

ByVal means the value which is assigned to the variable with in the function is temporary
and we can use that value only with in that function.

Example:

Function demo_parameters( byref x,byval y)
x=20
y=50
demo_parameters= x+y
End Function

a=10
b=20
msgbox demo_parameters( a,b)
msgbox a
msgbox b


In the above function x and y are the arguments, declared as byref and byval.
With in that function i assigned values to x and y.

Outside of the function i assigned values to two variables and passing those variables in to the function.
'a' is passing reference to x and b is passing value to y.

With in that function i am changing the value for x. This value is permanent for 'a'. Because 'a' is passed as 'ByRef'.

But the value of 'b' will not be changed because it is passed as 'ByVal'.

No comments:

Post a Comment