Option Base and Zero-Based Arrays

Programmers start counting at 0. The rest of the world starts counting at 1. Kemeny and Kurtz tell the story of how they dealt with this difference of opinion. Originally, the first dimension of a Basic array was 1 because thatís how normal people count and Basic was designed for normal people. But Basic also needed to work for mathematicians, who usually think of matrices as starting at 0, so Basic changed to start the first element at 0.

This wasnít so great either. Common sense tells you that in the statement Dim ai(10), the array ai contains 10 elementsóbut in fact it contains 11. That might be OK in C, where common sense is not a high priority, but it rubs Basic programmers the wrong way. So the Option Base statement was added, which lets you specify whether you want your arrays to make sense (start at 1) or be mathematically correct (start at 0).

Of course, as Pascal programmers knew all along, 1 and 0 arenít the only places you might want to start counting. Kemeny and Kurtz finally figured this out and changed Basic to let you specify the starting and ending points of arrays:

Dim ai(1 To 10) As Integer
Dim ad(0 To 49) As Double
Dim av(-10 To 10) As Variant

Kemeny and Kurtz didnít add this modification to Basic until 1979. ANSI Basic didnít get it until 1983. Microsoft Basic got it several years later. And I didnít figure it out until I wrote the first edition of this book. But now Iím a convert. I always use To when declaring arrays. Thereís nothing wrong with zero-based arrays, but you should declare the starting point specifically:

Dim asTitle(0 To 29) As String

Consider the extra five keystrokes cheap insurance against off-by-one errors.

Of course, that technique doesnít save you from needing to know that the default starting point is 0 in Basic-created arrays such as the controls array.

WARNING

If you buy my argument about always using To in array definitions, you must also stop making assumptions about the use of array elements. In other words, you canít assume that aBears(0) is the first bear in the array. An alternative rule used by many programmers is to completely avoid both To and Option Base 1. Thatís OK with me (although you wonít see it in this book). Just be sure that you donít mix the two approaches.