Scope of Variables


Scope of Variables

In this article, we hall continue our discussion on variables in Visual basic. We will also take a look at constants and the role they play in the working on a VB application

Scope of Variables

In most programs, unless you have only one form and no code modules, you'll find that you need some variables that can be accessed from anywhere in the code. These are called Public variables. (Also known as global variables.) These variables are typically for holding information that's used throughout the program. They can also be used to indicate various conditions in the program.

To create a Public variable, you place a declaration statement with the Public keyword in the Declarations section of a module of your program. The following line shows the Public declaration of a variable of type Boolean (True/False):

Public decision as Boolean

So why not make all variables Public (global)? This is the question asked by most novice programmers. Well, the answer is no because that defies what we term as  data hiding. A data set of a particular procedure is its private property. It doesn't  want any other module modifying its contents. Therefore arises the need of data members which are termed as local or static.

Constants

Constants are similar to variables but only have a single value throughout the execution of a program. The contents of variables can change as often as necessary. So why use a constant if it can only hold one value? Well often in a program it is necessary to use the same number or string repeatedly. For example, in a program to calculate end of year accounts there will be several parts of the program referring to the current value of V.A.T. We could hard code the value into the program everywhere it is used, but it would be tedious to change if the government altered the rate. Alternatively we could use a standard variable called 'VAT' to hold the value and set it on the Form_Load event. However, what happens if there is a bug in the program and the contents of this variable is changed accidentally to something else.

One solution which solves the above two problems is to use a constant. In the following example a constant named 'VAT' is declared and assigned the value 1.175. It is used in the Print statement with the variable bill_total to calculate the total bill amount. Notice that instead of writing 1.175 in the formula we refer to the constant by name.

Example:

 Const MAK = 1.175
The copyright of the article Scope of Variables in Learning Visual Basic is owned by Swapna Kamat. Permission to republish Scope of Variables in print or online must be granted by the author in writing.

Go To Page: 1 2

Articles in this Topic    Discussions in this Topic