ByVal vs ByRef

tchart

Well-Known Member
Licensed User
Longtime User
Maybe I something in the documentation, Ive noticed in my applications that that when I call a Sub routine the "variables" that are passed are a reference to the variable. WHich is the default for VB6 as well.

My question is, how to I pass a copy of the variable? The ByVal would achive this in VB6 but doesnt seem to be recognised in B4A.

Lastly are there any restrictions around passing arrays and custom types using the equivalant of ByVal in B4A?

Thanks
 

agraham

Expert
Licensed User
Longtime User
when I call a Sub routine the "variables" that are passed are a reference to the variable.
This is not in fact true. Basic4android, like Java which it compiles to, passes by value and does not have the capability of passing by reference. This means that it passes the value (contents) of a variable not a reference to it, so what is passed for a variable of primitive type is the value contained in the variable. For a variable of an array or object type what is passed is also the value contained in the variable but in this case it is a reference to the array or object instance in memory.

You cannot therefore pass a primitive variable ByRef to achieve the effect of returning multiple values from a method. The Java workaround, that Erel tipped me off about, is to pass an array(1) of the required primitive type and set the contents of that.
 
Upvote 0

tchart

Well-Known Member
Licensed User
Longtime User
Damn! :( pipped at the post by Erel whilst composing my impressively detailed reply!

Ah! Thanks guys that makes sense now. Now I know why my Rect was being mopdified in a Sub :D

Thanks for your answers.

Perhaps this should be added to the VB6 to B4A sticky?
 
Upvote 0
Top