By Kardi Teknomo, PhD .

< Previous | Next | VB Tutorial | Contents >

VB Pointer like in C = ByRef

Usually the code in a procedure needs some information about the state of the program (variables) to do its job. These variables consist of variables passed to the procedure when it is called. When a variable is passed to a procedure, it is called an argument . The arguments inputted into function or procedure can be passed using the value or by reference (pointer like in C programming language):

Passing Arguments by Value

Only a copy of a variable is passed when an argument is passed by value. If the procedure changes the value, the change affects only the copy and not the variable itself. Use the ByVal keyword to indicate an argument passed by value.

Passing Arguments by Reference

Passing arguments by reference gives the procedure access to the actual variable contents in its memory address location. As a result, the variable's value can be permanently changed by the procedure to which it is passed. Passing by reference is the default in Visual Basic. If you specify a data type for an argument passed by reference, you must pass a value of that type for the argument.

1. Make a new project and type the following code into Form_Click event procedure

Private Sub Form_Click()
       Dim intX As Integer
       Dim intResultByVal As Integer
       Dim intResultByRef As Integer
       intX = 2
       intResultByVal = MyFuncByVal(intX)
       MsgBox "Result ByVal = " & intResultByVal & vbCr & " intX = " & intX
       intResultByRef = MyFuncByRef(intX)
       MsgBox "Result ByRef =" & intResultByRef & vbCr & " intX = " & intX
End Sub
Private Function MyFuncByVal(ByVal x As Integer) As Integer
       x = x + 1
       MyFuncByVal = x
End Function
Private Function MyFuncByRef(ByRef x As Integer) As Integer
       x = x + 1
       MyFuncByRef = x
End Function

2. Run the program and now try to explain in your own word the difference between ByVal and ByRef

< Previous | Next | VB Tutorial | Contents >

Rate this tutorial or give your comments about this tutorial

This tutorial is copyrighted .