|
-
March 2nd, 2001, 07:33 PM
#1
parameter not passed byref
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?
-
March 2nd, 2001, 09:28 PM
#2
Re: parameter not passed byref
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
-
March 2nd, 2001, 09:38 PM
#3
Re: parameter not passed byref
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
-
March 3rd, 2001, 11:00 AM
#4
Re: parameter not passed byref
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|