Alex Rivera | Logout

ByRef and ByVal in VBScript

Asked 2009-10-08T13:33:17.833
34

I'm facing something weird in VBScript. When writing a procedure where I want the parameter to be passed by reference, the way of calling this procedure changes the way the parameter is passed !

Here is an example :

Sub IncrementByRef(ByRef Value)
   Value = Value + 1
End Sub

Sub IncrementByVal(ByVal Value)
   Value = Value + 1
End Sub

Dim Num
Num = 10
WScript.Echo "Num : " & Num
IncrementByRef(Num) : WScript.Echo "IncrementByRef(Num) : " & Num
IncrementByRef Num  : WScript.Echo "IncrementByRef Num : " & Num
IncrementByVal(Num) : WScript.Echo "IncrementByVal(Num) : " & Num
IncrementByVal Num  : WScript.Echo "IncrementByVal Num : " & Num

And here is the output :

U:\>cscript //nologo byrefbyval.vbs
Num : 10
IncrementByRef(Num) : 10
IncrementByRef Num : 11
IncrementByVal(Num) : 11
IncrementByVal Num : 11

U:\>

When specifying the the parameters are passed ByVal, it works as expected, no matter the way the procedure is called. But when specifying the parameters are passed ByRef, it will work as expected if calling the procedure this way :

IncrementByRef Num

but not this way :

IncrementByRef(Num)

This seems weird to me. Is there a way to make sure the parameters are passed ByRef, no matter how the procedure is called ?

Edit
Report

1 Answer

9

To be clear. Parentheses have three different purposes.

  1. Used to enclose an argument list when defining or calling procedure
  2. To indicate an indexer on an array.
  3. As an operator in an expression.

There are two ways to call a procedure either as a statement or as an expression.

Expression:-

x = func(y)

Statement:-

func y

Note the Call keyword invokes the procedure as if it were part of an expression hence the argument list must be contained in parantheses.

In the above that y itself represents a very simple expession. We could well have used y + z at this point. In fact we can use any valid expression at this point, including one that uses the parentheses operator. For example:-

 x = (y)

is a valid expression. Hence when you do:-

 func(y)

VBScript sees the call to func to which the result of the expression (y) is passed. Now even if func defines this parameter as ByRef the value in y would be unaffected because y wasn't actually passed as a parameter. What was passed was the result of the expression (y) which would be stored somewhere temporary. Even if this temporary store is modified by func it would be discarded afterwards and hence has the same behaviour had the parameter been marked ByVal.

answered 2009-10-08T16:33:21.777

Your Answer