Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

VARIABLES 119

they’re used by a couple of functions only. You can pass their values from one function to the other and avoid the creation of a new procedure-level variable.

The Lifetime of a Variable

In addition to type and scope, variables have a lifetime, which is the period for which they retain their value. Variables declared as Public exist for the lifetime of the application. Local variables, declared within procedures with the Dim or Private statement, live as long as the procedure. When the procedure finishes, the local variables cease to exist and the allocated memory is returned to the system. Of course, the same procedure can be called again. In this case, the local variables are recreated and initialized again. If a procedure calls another, its local variables retain their values while the called procedure is running.

You also can force a local variable to preserve its value between procedure calls with the Static keyword. Suppose the user of your application can enter numeric values at any time. One of the tasks performed by the application is to track the average of the numeric values. Instead of adding all the values each time the user adds a new value and dividing by the count, you can keep a running total with the function RunningAvg(), which is shown in Listing 3.7.

Listing 3.7: Calculations with Global Variables

Function RunningAvg(ByVal newValue As Double) As Double

CurrentTotal = CurrentTotal + newValue

TotalItems = TotalItems + 1

RunningAvg = CurrentTotal / TotalItems

End Function

You must declare the variables CurrentTotal and TotalItems outside the function so that their values are preserved between calls. Alternatively, you can declare them in the function with the Static keyword, as in Listing 3.8.

Listing 3.8: Calculations with Local Static Variables

Function RunningAvg(ByVal newValue As Double) As Double

Static CurrentTotal As Double

Static TotalItems As Integer

CurrentTotal = CurrentTotal + newValue

TotalItems = TotalItems + 1

RunningAvg = CurrentTotal / TotalItems

End Function

The advantage of using static variables is that they help you minimize the number of total variables in the application. All you need is the running average, which the RunningAvg() function provides without making its variables visible to the rest of the application. Therefore, you don’t risk changing the variables’ values from within other procedures.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com