ByRef and ByVal

ByRef gives other subroutines and functions the permission to make changes to variables that are passed in as parameters.  The keyword ByVal denies this permission and the parameters cannot be reassigned outside their local procedure.  ByRef is the Enable default and does not need to be used explicitly.  Because ByRef is the default all variables passed to other functions or subroutines can be changed, the only exception to this is if you use the ByVal keyword to protect the variable or use parentheses which indicate the variable is ByVal.

 

 

If  the arguments or parameters are passed with parentheses around them, you will tell Enable that you are passing them ByVal

 

SubOne var1, var2, (var3)

 

The parameter var3 in this case is passed by value and cannot be changed by the subroutine SubOne.

 

Function R( X As String, ByVal n As Integer)

 

In this example the function R is receiving two parameters X and n.  The second parameter n is passed by value and the contents cannot be changed from within the function R.

 

In the following code samples scalar variable and user defined types are passed by reference.

 

Scalar Variables

 

Sub Main

    Dim x(5) As Integer

    Dim i As Integer

    for i = 0 to 5

        x(i) = i

    next i

    Print i

    Joe (i), x  ‘ The parenthesis around it turn it into an expression which passes by value

    print "should be 6: "; x(2), i

End Sub

 

Sub Joe( ByRef j As Integer, ByRef y() As Integer )

    print "Joe: "; j, y(2)

    j = 345

    for i = 0 to 5

        print "i: "; i; "y(i): "; y(i)

    next i

    y(2) = 3 * y(2)

End Sub

 

Passing User Defined Types by Ref to DLL’s and Enable functions

 

 

' OpenFile() Structure

Type OFSTRUCT

   cBytes As String * 1

   fFixedDisk As String * 1

   nErrCode As Integer

   reserved As String * 4

   szPathName As String * 128

End Type

 

' OpenFile() Flags

Global Const OF_READ = &H0

Global Const OF_WRITE = &H1

Global Const OF_READWRITE = &H2

Global Const OF_SHARE_COMPAT = &H0

Global Const OF_SHARE_EXCLUSIVE = &H10

Global Const OF_SHARE_DENY_WRITE = &H20

Global Const OF_SHARE_DENY_READ = &H30

Global Const OF_SHARE_DENY_NONE = &H40

Global Const OF_PARSE = &H100

Global Const OF_DELETE = &H200

Global Const OF_VERIFY = &H400

Global Const OF_CANCEL = &H800

Global Const OF_CREATE = &H1000

Global Const OF_PROMPT = &H2000

Global Const OF_EXIST = &H4000

Global Const OF_REOPEN = &H8000

 

Declare Function OpenFile Lib "Kernel" (ByVal lpFileName As String, lpReOpenBuff As OFSTRUCT, ByVal wStyle As Integer) As Integer

 

Sub Main

    Dim ofs As OFSTRUCT

    ' Print OF_READWRITE

    ofs.szPathName = "c:\enable\openfile.bas"

    print ofs.szPathName

    ofs.nErrCode = 5

    print ofs.nErrCode

    OpenFile "t.bas", ofs

    print ofs.szPathName

    print ofs.nErrCode

End Sub