Forcing Variable Declarations VB Help

Visual Basic doesn’t enforce variable declaration, which is a good thing for the average programmer. When you want to slap together a “quick-and-dirty” pro-gram, the last thing you need is someone telling You Ito decide which variables you’re going to use and to declare them before using them.

But most programmers accustomed to the free format of Visual Basic also carry their habits of quick-and-dirty coding to large projects. When writing large appli-cations, you will probably find that variable declaration is a good thing. It will help you write clean code and simplify debugging. Variable declaration eliminates the source of the most common and pesky bugs.

If you have gotten spoiled, you can ask Visual Basic to. enforce variable declaration for you. To do so, place the following statement in the declarations section of ; a Form or Module:

Option Explicit

This statement tells the compiler to check each variable before using it and to issue an error message if you attempt to use a variable without declaring it. If you omit the Option Explicit statement, Visual Basic creates variables as needed.

The option Explicit statement must be included in every Module in which you want to enforce variable declaration. If you decide to declare all variables in your projects, you can ask Visual Basic to insert the Option Explicit statement automatically in every Module by checking the Require Variable Declaration checkbox in the Options dialog box (choose Tools> Options), as shown in Figure 3.2.

FIGURE 3.2

FIGURE 3.2

Let’s examine the side effects of implicit variable declaration in your application. You could use the following statements to convert German marks to U.s. dollars:

DM2USD =1.562
USDollars = amount  * DM2USD

The first time your code refers to the DM2USD variable name, Visual Basic creates a new variable and then uses it as if it was declared.

Suppose the variable DM2USD appears in many places in your application. If. in one of these places you type DM2USD instead of DM2USD and the program doesn’t enforce variable declaration, the compiler will create a new variable, assign it the value zero, and then use it. Any amount converted with the DM2UDS variable will be zero! If the application enforces variable declaration, the compiler will complain (the DM2UDS variable hasn’t been declared), and you will catch the error.

Many programmers, though, feel restricted by having to declare variables. Others live by it. Depending on your experiences with Visual Basic, you can decide for yourself. For a small application, you don’t have to declare variables. It’s too much typing. But for large applications that may take weeks or months to develop, you should consider variable declaration.

A Variable’s Scope

In addition to its type, a variable also has a scope. The scope of a variable is the section of the application that can see and manipulate the variable. If a variable is declared within a procedure, only the code in the specific procedure has access to that variable. This variable doesn’t exist for the rest of the application. When the. variable’s scope is limited to a procedure it’s called local.

Suppose you’re coding the Click event of a Common  button to calculate the sum of all even numbers in the range 0 to 100. One possibility is the following:

The variables i and Sum are local to the CommandClick()  procedure. If you attempt to set the value of the Sum variable from within another procedure, Visual Basic will create another Sum’variable and use it. But this won’t affect the variable Sum in the Command_Click() subroutine.

Sometimes, however, you’ll need to use a variable with a broader scope, such as one whose value is available to all procedures within the same Form or Module. These variables are called Form-wide (or Module-wide) and can be accessed from within all procedures in a component. In principle; you could declare all variables in the Form’s declaration section, but this would lead to problems. Every procedure in the Form would have access to the variable, and you would’ need to be careful not to change the value of a variable without good reason. Variables that are needed by a single procedure (such as loop counters, for example), should be declared in the procedure that uses them, not as Form variables.

Finally, in some situations the entire application must access a certain variable. In this case, the variable must be declared as Public. Public variables have a global scope they are visible from any part of the application). To declare a public variable, use the Public statement in place of the Dim statement. Moreover, public variables may not appear inside procedures. They must be declared as Form variables or in a Module.

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 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.

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 it new value and dividing by the count, you can keep a running total with the function RunningAvg(), which is shown next.

Capture

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:

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 re~t of the application. Therefore, you don’t risk changing the variables’ values
from within other procedures.

Variables declared in a Form outside any procedure take effect when the Form is loaded and cease to exist when the Form is unloaded. If the Form is loaded again, its variables are initialized, as if it’s being loaded for the first time ..

Constants

. .. ,
Some variables don’t change value during the execution of a program. These are constants that appear many times in your code. For instance, if your program does math calculations, the value of pi (3.14159… ) may appear many times in your code. These values are best represented by constants. Instead of typing the value 3.14159 over and over again, you can define a constant, name it pi, and use the name of the constant in your code. The following statement:

Area = 2 * pi * Radius

is much easier to understand· than the equivalent:

Area = 2 * 3.14159 * Radius

You could declare pi as a variable, but constants are preferred for two reasons:

  1. Constants don’t change value. This is a safety feature. Once a constant has been declared, you can’t change its value in subsequent statements, therefore,you can be sure that the value specified in the constant’s declaration will take effect in the entire program.
  2. Constants are processed faster than variables. When the program is running, the values of constants don’t have to be looked up. The compiler substitutes constant names with their values, and the program executes faster.

The manner in which you declare constants is similar to the manner in which . you declare variables, except that in addition to supplying the constant’s name you must also supply a value, as follows:

Canst constantname [As type] = value

The As type part of the declaration is optional. If you omit it, the constant’s type is determined by the value you assign to it. Constants also have a scope and can be Public or Private. The constant pi, for instance, is usually declared in a Module as Public so that every procedure can access it:

Public Const pi AS Double = 3.14159265358979

The constantname variable is a valid constant name that follows the same rules as variable names. The constant’s value is a literal value or a simple expression composed of numeric or string constants and operators. You can’t use functions in declaring variables. One way to define the value of pi is as follows:

pi = 4 * Atn(1)

However, you can’t use this assignment in the constant declaration. You must supply the actual value.

constant van be strings too, much as

Const ExpDate = ’31/12/1997
or:
Const ValidKey = ‘A567dfe’

Visual Basic uses constants extensively to define the various arguments of its methods and the settings of the various control properties. The value of a Check-Box control, for instance, can be 0 (unchecked), 1(checked), or 2 (grayed). Instead of using statements like:

Checkl.Value = 0
Check2.Value = 2

use the built-in constants vbUnchecked and vbGrayed:

Checkl.Value – vbUnchecked
Check2.Value – vbGrayed

Visual Basic’s constants are prefixed with vb, indicating that they are Visual Basic constants. The constants vbUnchecked and vbGrayed are built into the language, and you don’t need to declare them. Their symbolic names make the code much easier to read and maintain. Avoid the vb prefix when declaring your own constants. Other components of the language use different prefixes. For example, the Database Access Objects use constants with the prefix.

Constant declarations may include other constants. In math calculations, the value pi is as common as the value 2. * pi. You can declare these two values as constant:

Public Const pi As Double – 3.141592653SJ979
Public Canst pi2 As Double – 2 * pi

You can also create circular constant defination, such as the following:

Const constant1 = constant * 2
Const constant2 = constant 1/ 2

This circular definition doesn’t lead an, where (none of the constants has a value) and should be avoided.

It’s very unlikely that these two declaration will  appear in the same Module, but you may forget how you defined constant1; in one of the Modules and attempt to define constant2 in terms of constant1 in a not her Module. If this happens, Visual Basic generates a runtime error. If you declare all your constants in a single Module, they’re easier to maintain and chance.

Posted on November 4, 2015 in Visual Basic: The Language

Share the Story

Back to Top
Share This