| 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 | |
4-6: More on Nested If Statements
Exercise 4-4: Improving the Guessing Game (continued)
Declaring a Constant
One important matter remaining is to declare the variable MaxGuesses, and give it a value. The value of this variable should not change as the program executes - i.e. we should assign it a value and then that value should not change unless we edit the program to deliberately change it. This is different from other variables we have declared, which are designed to be assigned new values as the program executes.
There are many values that should never change - i.e. rather than being variable they are in fact constant. The value of pi and the gravitational constant are two examples from science and mathematics. But often values such as a sales tax rate (which is set by government rather than us) should also be constant within a computer program.
Such values should be declared as constants using the syntax
Const constName = constValue
which assigns a value
represented by the name, and which prevents a new value being assigned to that
name as the program executes.
In this case we should declare
Const MaxGuesses = 7
The remaining question is where we should place this declaration. Should it be a global declaration or should it be local to an event subprogram? Notice that the constant is used whenever the guessesRemainng variable needs to be reset. This occurs when the program first begins, i.e. in the New event of the Form, and whenever the user presses the Play Again button, i.e. in the _Click event of that button. Thus the constant should be declared globally.
The reason for declaring variables locally whenever possible is to prevent their value being changed inadvertently. However, the value of a constant cannot be accidentally changed and it is therefore common practice to declare constants globally. In any case, often constants need to be used throughout a program (i.e. in many of its subprograms), making the global declaration necessary anyway.