I am struggling to understand pass by value and pass by reference in VB6. I understand these concepts fully in Object Oriented programming languages like .NET and Java (I realise that Java doesn't have pass by reference). Have a look at the code below:
Private Sub Form_Load()
Dim Test As Integer
Test = 1
TestFunction Test 'line 5
MsgBox (Test)
End Sub
Private Sub TestFunction(ByVal i As Integer)
i = i + 1
End Sub
When I put brackets around Test on line 5, then the message box prints 1 as I would expect. Now have a look at the code below:
Private Sub Form_Load()
Dim Test As Integer
Test = 1
TestFunction Test 'line 5
MsgBox Test
End Sub
Private Sub TestFunction(ByRef i As Integer)
i = i + 1
End Sub
The message box prints 2 as I would expect. However, if you add brackets to line 5 then the message box prints 1 as I would not expect. It appears that the calling function can pass by value even if the variable defined in the called function is ByRef. It appears not to be the case vice versa, i.e. if the called function has a signature with a variable defined as ByVal then it will always be ByVal (even if there are no brackets around the variable in the calling function). What is the thinking behind this in VB6? I realize that this is a basic question in VB6 but it has confused me. I have read the MSDN documentation and I realize that this is all true, however it does not explain the reasoning behind it.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…