Click to See Complete Forum and Search --> : parameter not passed byref


JudsonCaspian
March 2nd, 2001, 06:33 PM
I ran the following code expecting the form's caption to be set to 10, but instead it was set to 5. Evidently i was passed byval instead of byref.

private Sub Command1_Click()
Dim i as Integer
i = 5
setToTen (i)
me.Caption = i
End Sub

Sub setToTen(byref n as Integer)
n = 10
End Sub




I'm using Windows 2000 Professional with VB6 (service pack 5). Does the above code pass the parameter by reference on other platforms?

Eric Powers
March 2nd, 2001, 08:28 PM
The default method in VB is byRef, you don't have to specify byref in the function.

The reason that you got the result you did is that even though you successfully called the function you didn't return the value to the variable; Here is a very concise code example that will produce the desired results;



private Sub Command1_Click()
Dim i as Integer
i = setToTen
me.Caption = i
End Sub

Function SetToTen()as integer
SetToTen = 10
end function





Hope this helps

JudsonCaspian
March 2nd, 2001, 08:38 PM
There is no need to return a value from a sub when the input is passed ByRef.

Evidently using parenthesis with a Sub causes the parameter be passed ByVal even when ByRef is explicitly indicated in the Sub's definition.

The following code correctly passes the input ByRef without using a return value:

private Sub Command1_Click()
Dim i as Integer
setToTen i 'no parenthesis
me.Caption = i
End Sub

Sub SetToTen(n As Integer)
n = 10
end function

CK Dixon
March 3rd, 2001, 10:00 AM
You know what happened?

When you passed as

SetToTen (i)

you must have noted that the function name and (i) have a space in between. The correct way of calling a function is either as you did

SetToTen i

or

Call SetToTen(i)

In this last case, you will note that the (i) and the function name have no space in between.

In

SetToTen (i)

what happened is that VB tried to evaluate the expression (i) and passed the result By Value, not the variable i By Reference as you wanted.