Variables

In Visual Basic, as in any other programming language, variables store values during a program’s execution. For example, you’re writing a program that frequently prompts the user for data, and you decide to add a personal touch to the interface. Every time the program needs data, it will display the user’s name. Instead of writing an application for Joe Doe, another for Mary Jones, and so on, .you can declare a variable that will store the user’s name. When the program starts, it asks the user to enter his or her name. It then stores this name in a variable and during the course of the program uses it to display the user’s name.

Variables are placeholders in which you can leave values and recall them at will. A variable has a name and a value. The variable UserName, for example, can have the value “Joe,” and the variable Discount can have the value 0.35. UserName and Discount are variable names, and “Joe” and 0.35 are their values. When a variable’s value is text (or string, as it’s called), it must be enclosed in double quotes. In your  code, you can refer to the value of a variable by the variable’s name. For example, the following statement calculates the discount for the amount of $24,500:

MsgBox ‘You will save • & 24500 * Discount

The message that this expression displays depends on the value of the Discount variable. If you decide to offer a better discount, all you have to do is change the value of the Discount variable. If you didn’t use the Discount variable, you’d have to make many changes in your code. In other words, if you coded the previous line as follows:

MsgBox ‘You save’ & 24500 * 0.35

you’d have to look for every line in your code that calculates discounts and change the discount from 0.35 to another value. By changing the value of the Discount variable in a single place in your code, the entire program is updated.

Declaring Variables

In most programming languages, variables must be declared in advance for the compiler. Historically, the reason for doing this has been to help the compiler. Every time a compiled application runs into a new variable, it.has to create it. Doing so doesn’t take a lot of statements, but it does produce a delay that could be avoided. If the compiler knows all the variables and their types that ate going to be used in the application ahead of time, it can produce the most compact and efficient, or optimized, code. For example, when you tell the compiler that the variable Discount will hold a number, the compiler will set aside a number of bytes for the Discount variable to use.

One of the most popular, yet intensely criticized, features of BASIC was that it didn’t force the programmer to declare all variables. As you will see, there are more compelling reasons than speed and efficiency for declaring variables. For example, if the compiler knows the types of the variables, it will catch many typing errors at design or compile time (errors that otherwise would surface at runtime). Later in the chapter, in the section “Forcing Variable Declarations,” you’ll see how variable declarations can simplify coding too.

Explicit Declarations

To declare a variable, use the Dim statement followed by the variable’s name and type, as follows:

Dim meters As Integer
Dim greetings· As String

We’ll look at the various data types in detail in the next section. In the meantime, you should know that a variable declared As Integer can store only integer numbers.

The first variable, meters, will store integers, such as 3 or 1002,and the second variable, greetings, will store text, such as “Thank you for using’ Fabulous Software”. You can declare multiple variables of the same type in the same line, as follows:

Dim meters As Integer, inches A-s Integer, centimeters As Integer

When Visual Basic finds a Dim statement, it creates one or more new variables, as specified in,the statement. That is, it creates a placeholder by reserving some space in the memory and assigning a name to it. Each time this name is used in subsequent commands, Visual Bask accesses this area in the memory to read or set its value. For instance, when you use the following statement:

meters = 23

Visual Basic places the value 23 in the placeholder reserved for the meters variable. When the program asks for the value of this variable, Visual Basic reads it from the same area of memory. The following statement:

Print meters

causes Visual Basic to retrieve the value 23 from the area of memory named meters. It’s also possible for a single statement to both read and set the value of a variable; The following statement increases the value of the meters variable:

meters = meters + 1

Visual Basic reads the value (say 23), adds 1 to it, and then stores the new value 24) in the same memory location.

One good reason for declaring variables is so that Visual Basic knows the type of information the variable must store and can validate the variable’s value. Attempting to assign a value of the wrong type to a declared variable generates a “Type Mismatch” runtime error.

For example, if you attempt to assign the value “Welcome” to the meters variable, Visual basic wont execute the statement because this assignment violates the variable’s declaration. The meters variable was declared as Integer, and you’re attempting to store a string in it. There are some interesting exceptions to this rule, For example, it’s possible to assign the value “103” to the meters variable (it’s a string, but it represents a numeric value) and to assign the value 103 to the greetings variable (it’s converted to the string “103” and then assigned to the string variable). We will look at more exceptions shortly, .

You can also declare variables without specifying their type, Visual Basic creates a generic variable that can hold any type, The following statement creates three variables of the variant type:

Dim temp, var , generic

A variant can store all types of values and is an extremely flexible data type, but it requires more overhead than variables declared with a specific type, For a detailed discussion of variants and how the)’ affect performance, see Chapter 12, Optimizing VB Applications.

Implicit Declarations

You can also choose not to declare variables. When Visual Basic meets an under cleared variable name, it creates a new variable on the spot and uses it, TI,e new variable’s type is variant, the generic data type that can accommodate all other data types. Using a new variable in your code is equiv lent to declaring it with out type, Visual Basic adjusts its type according to the value you assign to it Declare two variables, var1 and var2, with the following statement:

Dim var1, var2

and then assign a text value to one and a numeric value to the other:

var1 = ‘Thank you for using Fabulous Software’

var2 = 49.99

The var1 varibale is a string, and var2 is a numeric one, you can verify this with the typename() , which returns a variable ‘s,  the following statement print the types shown below:

Debug.Print ‘Variable var1 is & TypeName(var1)
Variable var1 is String
Debug.Print ‘Variable var2 is & TypeName(var2)
Variable var2 is Doub1e

tater in the same program you can reverse the assignments 49.99

var1 = 49.99
var2 = Thank you for using Fabulous Software·

If you execute the previous Print statements again, you’ll see that the types of the variables have changed. The varl variable is now a double, and .var2 is a string.

Finally, you can omit declaration statements, yet create typed variables with the variable declaration characters. To create a variable without declaring it, but that is still of a specific data type, add a suffix that is one of the data declaration characters in Table 3.1.

Capture

You can also declare variables using the Defxxx statements. For example you can declare that all variables beginning with a and b are integers, with the DefInt statement:

DefInt a-b

You can use the following statements to declare ranges of variables based on their first character:

Capture

Variable types that are declared with variable declaration characters and the Defxxx statements’ are leftovers from older versions of BASIC and an’, for the most part, obsolete.

Types of Variables

Visual Basic recognizes the following six types of variables:

  1. Numeric
  2. String
  3. Boolean
  4. Date
  5. Object
  6. Variant

The two major variable types are numeric and string. Numeric variables store numbers, and string variables store text. variant  variables can store any type of data. Why bother to specify the type if one type suits all? On the surface, using variants may seem like a good idea, but they have their disadvantages. Date variables are optimized for storing dates and object variables store objects (you’ll see how to use object variables in your code later in the book). We’ll use object variables  alot in Parts III and IV of the book. .

We beg.in. our. discussion of variable types with numeric variables. Text is stored in string variables, but numbers can be stored in many formats, depending on the size of the number and its precision. That’s why there are many types of numeric variables.

Numeric Variables

You’d expect (that programming languages would use a single data type for numbers. After all. ,a number is a number. But this couldn’t be farther from the truth. All programming languages provide a variety of numeric data types, including the following:

  1. Integers
  2. Single, or floating-point numbers with limited precision
  3. Double, or floating-point numbers with extreme precision

The names Single and Double come from single-precision and double-precision numbers. As you learned in Chapter 2, double-precision numbers are stored internally with greater accuracy than single-precision numbers. As you will see, there are many types of variables for storing numbers, and the reason is efficiency. For example, if you’re manipulating the pixels of an image, you’re calculating with integers. You don’t need more precision than integer numbers can provide, and using integers speeds up the calculations considerably. In scientific calculations, you need all the precision you can get (and then some more); in that case, you should use the Double data type.

Different types of numbers are represented internally in different formats. All numeric values are truncated to a certain extent. The result ot the operation V3 is 0.333333…(an infinite number of digits “3”). You could fill 16MB of RAM with the digit” “and the result would’still be truncated. Here’s a simple, but illuminating, example:

In a new Form’s Load event, declare two variables as follows:

Dim a. As Single, b As Double

Then enter the following statements:

a = 1/3
Debug. Print a

Run the application and you should get the following result in the Immediate window:

0.3333333

There are seven digits to the right of the decimal point. Break the application by pressing Control-Break and execute the- following statements in the Immediate window:

a = a * 100000
Debug. Print a

The following value will be printed in the Immediate window·

33333.34

The result is not as accurate as you might have expected initially it isn’t even rounded properly. If you divide s by 100000, the.result will be:

0·3333334

which is different from the number we started with (0.3333333). This is an important point in numeric calculations, and it is called error propagation. In long sequence of numeric calculations error propagate.

Let’s perform the same operations with double-precision numbers, this lime using the variable”. Add these lines to the Form’s Load event handler:

b = 1 / 3
Debug.Print b
b = b * 100090
Debug. Print b

This time. the following numbers are displayed in the Immediate window:

0.333333333333333
33333.3333333333

The results produced by the double-precision variables are more accurate.

NOTE

Smaller precision numbers are stored in fewer bytes and larger precision numbers are stored in more bytes, For example, integers are stored in two bytes, single precision floating-point numbers in four bytes, and double-precision, floating point numbers in eight bytes. The actual format of the floating-point numeric types is complicated and won’t be discussed in this book.

Numeric Data Types The choice of data types for your variables can make a difference in the results of the calculations. The proper variable types are determined by the nature of the values they represent. The choice of data types is frequently a trade off between precision and speed of execution (less precise data types are manipulated faster), Visual Basic supports the numeric data types in
Table 3.2,

Capture

Integers aft’ stored internally in two bytes, and Visual Basic handles integers efficiently, but you can represent only so many numbers with two bytes. Integers that exceed the specified range must be stored as Long integers. Long integers are stored in four bytes, and they cover a much larger range of values. If you know that a specific variable (such as a loop counter, for instance) will hold a small integer, declare it as an Integer. If the value of the integer may exceed the range of values that can be represented with two bytes, use a Long integer. Integer operations are faster and consume less memory than other data types.

If your variable can contain a fractional part, declare it as a Single, Double, or Currency data type. The Single data type is stored in four bytes, and the Double data type is stored in eight bytes. The main difference between the two types is not the range of values, but the accuracy with which values are represented. If you divide 5 by 3 as a Single data type, the result is: .

1.666667

If you divide 5 by 3 as a Double data type, the result is:

1.66666666666667

The Double data type provides more accuracy, which is needed in mathematical calculations. If you don’t need more than a couple of fractional digits, use the Single data type. If you’re concerned about accuracy, use the Double data type. AIong use the Double data type if you’re going to perform a series of math operations a; id the result of one operation will be used as an operand for the next. A little accuracy lost at every operation may substantially alter the final result.

The Currency data type can store fixed-point numbers and is suitable for.financial calculations that don’t need more accuracy than two fractional digits. This type supports four digits to the right of the decimal separator and 15 digits to the left. This accuracy is adequate for financial calculations, but not for scientific calculations.

The Byte Data Type None of the numeric types is stored in a single byte. In some situations, however, data is stored as-bytes, and you must be able to access individual bytes. The Byte type holds basically an integer in the range 0 fa 255. Bytes are frequently used to access binary files, image and sound files, and so on. Some Windows Application Programming Interface (API) calls also use Byte arguments. API is a powerful set of functions that form the core of the operating system and they are discussed in Chapter 13. An argument is a value you pass to the procedure and on which the procedure usually acts. To declare a variable as a Byte, use the following statement:

Dim n As Byte

.
The variable can be used in numeric calculations too, but you must be careful not to assign the result to another Byte variable if its value may exceed the range of the Byte type. If the variables A and B are h initialized as follows.

Dim A as byte, B as byte
A = 233
B = 50

the following statement will display the correct result, even though it exceeds the value range of the Byte type:

MsgBox A + B

However, attempting to’assign this value to a Byte variable with the following statement will generate an overflow runtime error:

B=  A + B

The result (288) can’t be stored in a single byte. Visual Basic generates the correct answer and stores it internally as an integer; that’s why it can display the answer with the MsgBox function. But the assignment operation fails because the. result can’t fit in a single byte .

The operators that won’t cause overflows are the Boolean operators AND, OR, NOT, and XOR,which are frequently used with Byte variables. These aren’t logical operators that return True or False. The}’ combine the matching bits In the two operands and return another byte. If you combine the numbers 199 and 200 with the AND operator, the result is 192. The two values in binary format are
11000111 and 11001000. If you perform a bitwise AND operation on these two values, the result is 11000000, which is the decimal value 192.

Accuracy of Numeric Types The smaller the integer part of a floating-point number, the more fractional digits.it can hold. For example, the result of the operation 5 divided by 3 expressed as a Double data type is:

1.66666666666667

The result of the operation 500000 divided by 3 expressed as 11 Double data type doesn’t have as many fractional digits, however. Visual Bask reports the number follows:

166666.666666667

The number had to be truncated at the ninth digit after the decimal.point because  Visual Basic has eight bytes in which to fit the number. Some bytes of the larger number arc allocated to the integer part, so there are fewer bytes left to represent the fractional part,

Scroll to Top