ByVal transfers a copy of the parameter memory to the callee. In other words, the value that is directly pushed into the stack is the passed value.
ByRef transmits the actual address of the parameter memory to the callee. In other words, what is pressed into the stack is the address of the actual content. The callee can directly change the contents in the address.
ByVal is the value source data that will not be modified
You can use this value as your own local variable
ByRef is the pass address, the source data may be modified
Your operation on this variable will have an impact on the variable you pass in, just like the feeling of a pointer
Example:
The code copy is as follows:
subAdd1(ByValnoasint32)
no=no+100
endsub
subAdd2(ByRefnoasint32)
no=no+100
endsub
privatesubbutton1_click(senderasobject,easventargs)handlesbutton1.click
dimaasint32
a=100
Add1(a)
msgbox("a is: "&a)' shows that the value of a is 100
Add2(a)
msgbox("a is: "&a)' shows that the value of a is 200, because the parameter no in Add2 is ByRef, that is,
'Passed by address, so after modifying no in Add2, it will cause
'The value of source parameter a is also modified.
EndSub
——————————————————————————————————————
3. ByVal and ByRef
The parameter value passed by ByVal, and the address of the parameter passed by ByRef. Here, we don’t have to distinguish between pointers/addresses/references. In VB, they are simply three different statements about one thing. Even VB documents are mixed with these terms (but in C++, we do need to distinguish between pointers and references)
Friends who are first exposed to the above program 2 SwapPtr must figure out where to add ByVal and where not to add (not adding ByVal is to use the default ByRef of VB)
Accurately understanding the difference between passing values and passing addresses (pointers) is the basis for correct use of pointers in VB.
Now, a simplest experiment is used to look at this problem, such as the following procedure three:
【Program Three】: Experience ByVal and ByRef
The code copy is as follows:
Sub TestCopyMemory()
Dim k As Long
k = 5
Note: CopyMemory ByVal VarPtr(k), 40000, 4
Debug.Print k
End Sub