Home > Blockchain >  How does VBA ByRef work behind the scenes?
How does VBA ByRef work behind the scenes?

Time:05-08

Let's say I have a function that takes an Integer value ByRef, like this:

Function myFunc(ByRef funcVal As Integer)
  funcVal = funcVal   1
End Function

And let's suppose I call it like this:

Dim myVal as Integer
myVal = 5
Call myFunc(myVal)

As I understand it, the computer has allocated space for my myVal variable and put the value 5 in that space. When I call myFunc, the computer basically passes a pointer to that location to myFunc, so that when myFunc increments funcVal, it is actually incrementing the same location, so myVal is also incremented.

But what happens if instead I call myFunc like this:

Call myFunc(5)

Does the computer still give myFunc a pointer, and if so a pointer to what? Or does it have to assign some fresh space to funcVal (instead of just using the same space as myVal like it did in my previous example)?

I suppose there's also a related question here - how does VBA handle literal values in the code?

Many thanks!

CodePudding user response:

Variables are stored at memory addresses. So are literals. So are procedures. AND SO ARE PROCEDURE PARAMETERS.

Parameters are locally scoped variables and they are distinct and separate entities from arguments passed to the procedure. The VB virtual machine manages all these entity addresses in a table.

When a variable argument is passed by reference a pointer is passed to the associated procedure parameter and this gives the parameter direct memory access to the calling variable address.

HOWEVER, literals themselves are obviously immutable, so when a literal argument is passed by reference, the VM is forced to make a copy of the literal to a temporary address and this new address is passed by reference to the procedure. This allows the procedure to use AND UPDATE the value during execution without affecting the original literal value outside of the procedure.

In essence literals are always passed by value and passing by value actually means passing a pointer to a copy of the calling argument.

  • Related