Visual Basic recognizes the following five categories of variables:
The two major variable categories are numeric and string. Numeric variables store numbers, and string variables store text. Object variables can store any type of data. Why bother to specify the type if one type suits all? On the surface, using object variables might seem like a good idea, but they have their disadvantages. Integer variables are optimized for storing integers, and date variables are optimized for storing dates. Before VB can use an object variable, it must determine its type and perform the necessary conversions. If the variable is declared with a specific type, these conversions are not necessary.
We begin 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. The String and Date data types are much richer in terms of the functionality they expose, and are discussed in more detail in Chapter, ‘‘Handling Strings, Characters, and Dates.”
You’d expect that programming languages would use the same data type for numbers. After all, a number is a number. But this couldn’t be further from the truth. All programming languages provide a variety of numeric data types, including the following:
- Integers (there are several integer data types)
- Single, or floating-point numbers with limited precision
- Double, or floating-point numbers with extreme precision
Decimal, Single, and Double are the three basic data types for storing floating-point numbers (numbers with a fractional part). The Double data type can represent these numbers more accurately than the Single type and is used almost exclusively in scientific calculations.
The Integer data types store whole numbers. The data type of your variable can make a difference in the results of the calculations. The proper variable types are determined by the nature of the values they represent, and the choice of data type 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 shown in Table 2.1. In the Data Type column, I show the name of each data type and the corresponding keyword in parentheses.