Passing Arguments by Value and by Reference

You can pass arguments to a function by value or by reference. Passing an argument by value means that a copy of the argument is sent to the function. Passing arguments by value means that the function cannot change the value of the actual argument because it is only working with a copy of the argument.

Passing an argument by reference means that the function is actually passing a 32-bit pointer to the memory address where the value of the argument is stored. When an argument is passed to a function by reference, it is possible for the function to actually change the value of the argument because the function is working with the actual memory address where the argument's value is stored and not just a copy of the argument's value.

With Windows API functions, the passing of arguments by value or by reference is not simply a matter of choice by the programmer. The functions that make up the Windows API expect its arguments to be passed either by value or by reference. It is up to you, the programmer, to know the proper way to pass arguments to a particular function. If you pass an argument by value when the function expects the argument to be passed by reference, or vice-versa, the function will receive the wrong type of data and will probably not work correctly. And when you're dealing with system-level functions, the results can be very unpredictable indeed.

Visual Basic, by default, passes arguments to functions by reference. It is not necessary then, when writing a Declare statement, to explicitly pass an argument to the function using the ByRef keyword. When passing arguments by value, however, you must explicitly use the ByVal keyword.

Some Windows API functions that require more than one argument might have some arguments that must be passed by value and some arguments that are passed by reference. In this case, you have to use ByVal for the arguments passed by value, but you can use the ByRef keyword or leave it out for arguments passed by reference.

The following code shows an example of a Declare statement that declares a function that requires some arguments to be passed by value and some to be passed by reference:

Declare Function CreateIcon& Lib "user32" (ByVal hInstance As Long, _
   ByVal nWidth As Long, ByVal nPlanes As Byte, ByVal nBitsPixel As Byte, _
   lpANDbits As Byte, lpXORbits As Byte)
Two of the arguments to this function, lpANDbits and lpXORbits, are passed by reference (the default), whereas the other arguments are passed by value.
Top Home