CST2601 Visual
Basic I
Notes on Static variables
Static VariablesIn addition to scope, variables have a lifetime, the period of time during which they retain their value. The values in module-level and public variables are preserved for the lifetime of your application. However, local variables declared with Dim exist only while the procedure in which they are declared is executing. Usually, when a procedure is finished executing, the values of its local variables are not preserved and the memory used by the local variables is reclaimed. The next time the procedure is executed, all its local variables are reinitialized. However, you can preserve the value of a local variable by making the variable static. Use the Static keyword to declare one or more variables inside a procedure, exactly as you would with the Dim statement:
For example, the following function calculates a running total by
adding a new value to the total of previous values stored in the static
variable
If You can produce the same result by declaring Declaring All Local Variables as StaticTo make all local variables in a procedure static, place the Static keyword at the beginning of a procedure heading. For example:
This makes all the local variables in the procedure static regardless of whether they are declared with Static, Dim, Private, or declared implicitly. You can place Static in front of any Sub or Function procedure heading, including event procedures and those declared as Private. |