Sub returns a value???

DataMiner

Registered User.
Local time
Today, 16:40
Joined
Jul 26, 2001
Messages
336
Okay, this has got me freaked out, as I didn't think this could happen:
I expect Sub FirstSub to print "27", but it prints "32". How can this be??? I thought a Sub would only perform a task, NOT return a value? All the years I have been programming, I have assumed that sending a value to a Sub was a "one way" thing.... Have I just had it wrong all these years??? Can somebody please explain this to me??? :eek:
Is it something to do with the way I have the variables scoped?

Sub FirstSub
dim x as integer
x=27
SecondSub x
debug.print x
end sub

Sub SecondSub(n as integer)
n=n+5
end sub
 
Last edited:
Your version of Access is passing the procedure's argument by reference, the default -- at least in Access 2000. This means the second sub uses the argument named "n" to point to the variable named "x" in the first sub -- that is, it references the same memory space as variable x. The result: what n does to the variable affects x since they both point to the same memory space.

If you don't want this to happen, you must explicity tell Access to pass the argument by value... This means the second sub will create a brand new variable named "n" pointing to an area of memory distinct from the area occupied by x. The result: what happens to "n" in the second sub doesn't affect "x" in the first sub.

Here's how you can make sure a procedure's argument is passed by value...

Code:
' Pass the argument by value.
Sub SecondSub(ByVal n As Integer)
  n = n + 5
End Sub

Regards,
Tim
 
Thanks! I feel sorta stupid that I didn't know that... seems like a fairly important thing to know!
 
Thanks! I feel sorta stupid that I didn't know that

I feel like that about once a week...goes with the territory. Happy to have helped...

Regards,
Tim
 
Last edited:

Users who are viewing this thread

Back
Top Bottom