Home

Static Variables

 
 

Introduction

 

Consider the following program: 

Public Module Exercise

    Private Sub Starter(ByVal y As Integer)
        Dim a As Double = 112.5
        Dim b As Double = 175.25
        Dim Result As String

        a = a / y
        b = b + 2

        Result = "y   = " & vbTab & CStr(y) & vbCrLf & _
                 "a   = " & vbTab & CStr(a) & vbCrLf & _
                 "b   = " & vbTab & CStr(b) & vbCrLf & _
                 "b/a = " & vbTab & CStr(b / a)
        MsgBox(Result)
    End Sub

    Public Function Main() As Integer
        Starter(2)
        Starter(2)
        Starter(2)
        Starter(2)

        Return 0
    End Function

End Module

When executed, this program would produce:

Static Variables

Static Variables

Static Variables

Static Variables

The Starter() procedure receives one argument passed when it is called. This procedure also receives the same argument every time. Looking at the result, the argument passed to the procedure and the local variables declared inside of the called procedure keep the same value every time the procedure is called. That is, when the Starter() procedure exits, the values remain the same.

We know that, when a procedure is defined, any variable declared locally belongs to the procedure and its influence cannot expand beyond the body of the procedure. If you want a locally declared variable to keep its changed value when its host procedure is exited, declare such a variable as static.

 
 
 

Declaring a Static Variable

To declare a static variable, type the Static keyword on the left of the Dim keyword. You should always initialize a static variable before using it. To make the local variables of our Starter() function static, we can declare them as follows: 

Public Module Exercise

    Private Sub Starter(ByVal y As Integer)
        Static Dim a As Double = 112.5
        Static Dim b As Double = 175.25

        Dim Result As String

        a = a / y
        b = b + 2

        Result = "y   = " & vbTab & CStr(y) & vbCrLf & _
                 "a   = " & vbTab & CStr(a) & vbCrLf & _
                 "b   = " & vbTab & CStr(b) & vbCrLf & _
                 "b/a = " & vbTab & CStr(b / a)
        MsgBox(Result)
    End Sub

    Public Function Main() As Integer
        Starter(2)
        Starter(2)
        Starter(2)
        Starter(2)

        Return 0
    End Function

End Module

This time, when executing the program, it would produce: 

Static Variables

Static Variables

Static Variables

Static Variables

Notice that, this time, each local variable keeps its newly changed value when the function exits.

 
 
   
 

Home Copyright © 2008-2016, FunctionX, Inc., Inc.