Sunday, July 19, 2009

Difference between call by value and call by reference?

ByVal
Indicates that the argument is passed by value.
ByRef
Indicates that the argument is passed by reference.

Call Statement
Transfers control to a Sub or Function procedure.

[Call] name [argumentlist]
Arguments
Call
Optional keyword. If specified, you must enclose argumentlist in

parentheses. For example:
Call MyProc(0)

name
Required. Name of the procedure to call.
argumentlist
Optional. Comma-delimited list of variables, arrays, or expressions to

pass to the procedure.


Remarks
You are not required to use the Call keyword when calling a procedure.

However, if you use the Call keyword to call a procedure that requires

arguments, argumentlist must be enclosed in parentheses. If you omit

the Call keyword, you also must omit the parentheses around

argumentlist. If you use either Call syntax to call any intrinsic or

user-defined function, the function's return value is discarded.




var="Hello World"
Call MyFunction(var)
msgbox var
Function MyFunction(byval text)
text = "gopi"
End Function
'output of the above pgm is "Hello World"


var="Hello World"
Call MyFunction(var)
msgbox var
Function MyFunction(byref text)
text = "World is Changed"
End Function
'output of the above pgm is "World is Changed"


Passing by Value is just that. It passes a value to the function to use. It creates a new space to hold this value.

Passing by Reference passes the pointer to the memory space for the variable. This means that anything you do to the variable in the function changes the actual value of the passed variable. This means that if you changed the variable in the function it will be changed outside the function too.

1 comment: