Return value of static function

kassyopeia
08-07-2009, 11:50 AM
Am I correct in thinking that the return value of a static function is non-static? I.e., that the variable a implicitly declared in
Public Static Function a() As Long
will be initialized to zero each time the function is called? Or am I missing some subtlety?

passel
08-07-2009, 02:11 PM
I don't know if you're missing some subtlety or not.
Declarating the function as static means that all the local variables within the function are static and will maintain their values between invocations.
The function name itself is not a local variable, even though VB allows you to generally treat it as if it were.
I prefer to use a declared local variable in my function and "Return" it by assigning the local variable to the function name when I exit.
If you do that, and the local variable is not modified during the execution of the function, the function will return the previous value of the local variable.

You are correct in that the return value of a function is always zero if the return value is not changed by the function.

kassyopeia
08-07-2009, 02:46 PM
The function name itself is not a local variable, even though VB allows you to generally treat it as if it were.
Ah, okay, I guess that's why I was unsure of what was happening. I always thought of the entity that we assign the return value to as precisely that, an ordinary local variable, except that it's declared implicitly at the start and read out at the end.
I prefer to use a declared local variable in my function and "Return" it by assigning the local variable to the function name when I exit.
Yes, I do that too, but thought of it as simply a habit from other languages.

What brought up the question was my would-be-insight that this

Public Static Function getSingleton() As singletonClass
If getSingleton Is Nothing Then Set getSingleton = New singletonClass
End Function

does the same as this

Private singletonObject As singletonClass

Public Function getSingleton() As singletonClass
If singletonObject Is Nothing Then Set singletonObject = New singletonClass
Set getSingleton = singletonObject
End Function

which didn't work (object doesn't become persistent) because of what you just explained.

Thanks. :)

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum