Data Types
Basic started as a language with only two data types: numbers and strings. It might seem as though the language has come a long way to user-defined types, forms, and classes in the current version, but you could make a case that Basic has actually gone the other way, becoming a language with only one type—which essentially means a typeless language. To state it more accurately, Basic has become a language with two modes: typed and typeless.
As you’ll see in Chapter 4, typeless mode (using Variant for all variables) is increasingly important. Features such as parameter arrays and collections work only in typeless mode. On the other hand, optional arguments, which used to work only for variants, now work for any type. That throws some confusion into what I’m about to propose. Nevertheless, full steam ahead.
Visual Basic allows a variety of programming styles for handling variable declarations (or the lack of same). No other language offers such flexibility. In Pascal or C, you declare the type of each variable at the top of the procedure, and that’s that. In Basic, you don’t need to declare any variables except arrays, but if you choose, you can make Basic as strict about variable declarations as Pascal. Let’s look back at the history of Basic to understand where this confusion came from.
For Ever
Everyone knows how a For loop works. Well, maybe. Consider this loop:
For i = 1 To Len(s)
‘ Do something with characters of string s
Next
This For loop is a shortcut for a Do loop like the following:
i = 1
Do While i <= Len(s)
‘ Do something with characters of string s
i = i + 1
Loop
The comparison is not exact, however. What if the statements in the loop change the length of the string s by deleting or adding characters? In fact, something very different is happening. In the Do loop, the length of the string is checked every time through; in the For loop, it’s checked only once. So the Do loop equivalent of the For loop is actually this:
i = 1
iTemp = Len(s)
Do While i <= iTemp
‘ Do something with characters of string s
i = i + 1
Loop
There are two morals to this story:
-
To write efficient Do loops, try to keep While and Until tests simple. Don’t test the length of a string every time through the loop if you know that the length won’t change. Consider reorganizing simple Do loops into For loops.
-
If you’re changing what’s being tested inside the loop, consider changing a For loop to a Do loop. Another trick that sometimes works is to process a For loop backward, changing only items that have already been counted. The following loop, which removes selected items from a list box, works as written, but it would fail if you counted forward, because deleting items changes the list count and the current item:
For i = lstData.ListCount - 1 To 0 Step -1
If lstData.Selected(i) Then lstData.RemoveItem i
Next