Where to declare variables -- an example

I set out to write a program that would count the number of times I clicked on a button.

The external description was very simple: The user interface would have a button and a label, and when the user clicked on the button, the label would increase by one, counting the number of clicks.

The handler for the event of the user clicking the button was also simple. With every click, the program would add one to an integer variable, then display its value using the label.

I created the user interface, naming the button btnClick and the label lblCounter.

Private Sub btnClick_Click ...
   Dim count As Integer            'construct the click count variable
   count = count + 1               'add one to the count
   lblCounter.Text = CStr(count)   'display the count
End Sub

When I ran the program to test it, it did not work as I had imagined it would. The first click worked fine, with the count increasing from 0 to 1, but subsequent clicks had no effect -- the count was stuck at 1.

I discovered the problem by stepping carefully through the program in my mind, noting how the value of the variable count changed as each instruction executed.

The first time the user clicked the button, the event handler executed the three instructions. The first instruction constructed count and assigned it the default value of 0. The second instruction increased its value to 1, and the third instruction displayed it. Since the variable is declared inside the event handler, it is automatically destroyed after the event handler finishes. The space reserved for it in memory is returned so that it can be reused.

The second time the user clicked the button, it did the same thing. The problem was that the first thing the event handler did was to re-construct the variable count and reset its value to 0.

To fix the bug, I moved the declaration of the variable outside the event handler, so that it was only executed one time (just after the program loaded):

Dim count As Integer               'construct the click count variable
Private Sub btnClick_Click ...
   count = count + 1               'add one to the count
   lblCounter.Text = CStr(count)   'display the count
End Sub

Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.