Sunday, 24 November 2013

QTP Passing Parameters to a Function/Sub - Pass By Value & Pass By Reference



You can pass parameters to a function or sub procedure by value or by reference. Let’s see what both these terms mean.

Passing Parameters by Value (byVal).

 With this way of passing parameters, only a copy of the original parameters is passed. This means that whatever modifications we make to the parameters inside the function, it doesn’t affect the original parameters.


Sample Code 1: Passing parameters by value to a function

Dim val
val=5

'Function Call
fnFunc val
msgbox "Original Value: " & val 'msgbox displays value 5

'Function Definition
Function fnFunc(byVal val)
  val = val + 2
  msgbox "New Value: " & val 'msgbox displays value 7
End Function

In the above example you would see that the new value get changed to 7 but it doesn’t get reflected to the original value which still shows the value as 5 only.


Passing Parameters by Reference (byRef).

In this case, the reference of the original value is passed as the parameter to the function. Therefore, whatever change is done to the parameter inside the function, the same is reflected in the original parameter also. By default, values are passed by reference in a function. i.e., even if you don’t use byRef keyword, the parameters are passed by reference.


Sample Code 2: Passing parameters by reference to a function

Dim val
val=5
'Function Call
fnFunc val
msgbox "Original Value: " & val 'msgbox displays value 7
'Function Definition
Function fnFunc(ByRef val)
  val = val + 2
  msgbox "New Value: " & val 'msgbox displays value 7
End Function

Since the original parameter is passed as reference to the function, both the original and new value has the updated value 7.

No comments:

Post a Comment