| Chapter 3- Data Types and Operators | Boolean Expressions Page 2 3 4 |
| The If Statement Page 2 3 4 5 6 7 8 9 | |
| Arithmetic Operations Page 2 3 4 5 6 | Boolean Operators and Nested If Statements Page 2 3 4 5 6 7 |
| Events and Sequential Processing Page 2 3 4 5 | More Examples Page 2 3 4 5 6 7 8 9 10 11 12 |
| Datatypes and Conversions Page 2 3 4 5 6 7 | Using Check Box and Option Controls Page 2 3 4 5 6 7 8 9 10 |
| Variable Declarations - Local and Global Page 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Exercises Page 2 3 4 5 6 7 8 |
| Chapter 4- Selection Statements | Review Questions |
| Introduction | |
3-5: Variable Declarations (continued)
You should be able to run the program having entered only this small piece of code. Click on the NextYr button and observe what happens. You should find that the value in the Year textbox becomes 1 after the first click. Click again. You should find that the value remains 1, when you had been expecting it would increment to 2!
The reason for this is due to the location of the variable declaration. Remember that the code within the event is carried out every time the button is clicked. In other words the declaration of the variable also occurs every time the button is clicked! When a variable is declared it is set to an initial value by default - 0 in the case of integer variables. Thus, every time the button is clicked the Year variable gets set to 0, then 1 gets added and then the value (now 1) is assigned to the Text property of the Year textbox.
More than this, in fact when the event subprogram has finished (i.e. all the statements have been executed) the memory cells used by any variables declared within the subprogram are reclaimed by the computer. That is the variables cease to exist!
This is the meaning of a local variable. It exists only while the subprogram within which it is declared is executing.
Thus for this problem, where we want the value of the Year variable to remain from one click of the button to the next rather than being set to zero each time, it is wrong to declare the variable locally (within the event).