Simberon Design Minute
 

Zero Based Or One Based Arrays

One topic that's sure to trigger a language debate is whether arrays should be indexed starting at zero or at one. Programming languages like C use zero-based arrays because they use pointer arithmetic to index the elements and the first element is at offset zero from the pointer to the start of the Array. Java carried on this tradition even though Java doesn't have pointer arithmetic. Smalltalk uses one-based arrays so the first element of the array is at index 1 and the second is at index 2. Which approach is better? It turns out in practice, each solution has its advantages and disadvantages. The C approach of zero-based arrays produces faster optimized code but ties you in to a low-level way of thinking about the collection. When someone says that the fourth element of the array has some value, it's unnatural to have to look at index 3. With one-based arrays, the element number and the index are the same. The fifth element is at index five. There are cases, however, where one-based arrays incur a lot of extra work. If you're trying to implement multi-dimensional arrays or you're working with images, it works out better if the indices start at zero so modulo operations work properly and you don't need to continually add or subtract one to get the proper index. The real answer to the zero or one based indexing problem is "it depends what you're doing".

Download