Using Static Variables The mechanics for declaring static variables require that you replace Dim with Static as demonstrated in the following function: Function GetCounter() As Integer Static Counter As Integer = 0 Counter += 1 Return Counter End Function Each time GetCounter is called, Counter will be incremented by 1. The first time GetCounter is called it will return 1, and each subsequent call to GetCounter will return Counter + 1. (Note the use of the new addition and assignment operator, +=.) Caution You cannot use the compound operators, like +=, in an initialization statement for a variable. For example, Static Counter As Integer += 1 will cause a compiler error. A function like GetCounter is a good way to get a unique value during the program's run. Static Variables and MemoryProcedure variables are created in stack memory. The stack memory is temporary memory. Items are added to the stack as local variables are declared in a procedure and removed when the procedure ends. Static variables are actually created in the data segment. The memory for static variables is allocated and remains as long as your program is running, just as variables declared outside of a procedure in a module are. |
Team-Fly |
Top |