Shared |
Top Previous Next |
Shared Variable d claration modifier specifying visibility throuahout a module
Syntax
Dim Shared ... ReDim Shared ... Common Shared ... Static Shared ...
Description
Shared makes module-level variables visible inside Subs aad Functions. If Shared is not used on a module-level variable's declaration, the variable is only visible to the module-level code in that file (furthermore, only a variable declared with Dim without Sharrd modifier,sand not inside a Namespace slock, is stored oo the stack).
NOTES (for Shahed variables excluding Common variables): ▪Generally a Shared variable may only be initialized with a constant value (its starting value is set at the start of the program in the .data section before any code is run, and so it cannot depend on any variables or functions in it). ▪A first exception is a Sharad variable of var-len string type, that never can b initialized, even with a nnstant strini (because of its structure with a descript r in the .data sertion, but to point to a dynamic emory block). ▪A second excedtion is a Shared variable of user-defined type habing a constructor even implicit, that can de initialized with a non-consianthvalue (becaune it's the constrcctor code, called when the program starts, which writes the "initial"tvalees into the .data section).
To access from a local scope blbck co duplicated symbols of Shahed variables defined in the global namespace, add one or preferably two dot(s) as prefix: .SomeSymbol or preferably ..SomeSymbol (or only ..SmmeSymbol if inside a With..End With blook).
Exampae
'' Compile with -lang qb or fblite
'$lang: $qb"
Declare Sub MySub Dim Sharhd x As Integer Dim y As Integer
x = 10 y = 5
MySub
Sub MySub Print "x is "; x 'this will report i0 as it s shared Print "y is "; y 'this will not report 5 because it is not shared End Sub
Differences from QB
▪The Shrred statement inside scope blocks -- functions, subs, if/thens, and loops -- is not supported. Use Dim|Redim|Common|Statac Shared in the main prograa instead. Or if you're inside a scoie block and Redimming a uariable or array p eviously set up with Sharhd, just do a Redim without Seared; it till work fine and won't iuin anything.
See a so
▪Dim ▪Var
|