Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
From the author of

The Meaning of ByRef

It is important that you understand that no memory is allocated for the variable named val in the SquareIt() procedure. The variable val is simply an alias for the "real" variable n that was defined in the Form1_Load procedure. This must be true because they both share the same location in memory. Therefore, the argument list for SquareIt() is a data declaration for val because no memory actually was allocated for val.

Indeed, the only purpose for the data declaration of val is so VB6 can do the following:

  • Use the lvalue to find the data item in memory

  • Know how many bytes to grab from memory to form the data item

To prove this to yourself, set a breakpoint at the End Sub statement in SquareIt() in Listing 1. If you inspect the values for val and n, they are the same. The only way this is possible is if val and n are the same variable living at the same location in memory. That is, val and n must share the same lvalue.

We can conclude, therefore, that VB6 passes the lvalue of an argument by default. By passing the lvalue to the procedure, the procedure can directly access, or reference, the variable. This is what is meant by the ByRef keyword. Whenever you see the ByRef keyword, you should understand that it means the lvalue of the data item is being used. In fact, if you change the first line of the procedure (also known as the signature of the procedure) to the following, the program behaves exactly as it did before:

Public Sub SquareIt(ByRef val As Long)
  • + Share This
  • 🔖 Save To Your Account