What's the purpose of arrays starting with nonzero index?

Posted by helios35 on Stack Overflow See other posts from Stack Overflow or by helios35
Published on 2011-01-14T13:45:51Z Indexed on 2011/01/14 13:53 UTC
Read the original article Hit count: 136

I tried to find answers, but all I got was answers on how to realize arrays starting with nonzero indexes. Some languages, such as pascal, provide this by default, e.g., you can create an array such as

var foobar: array[1..10] of string;

I've always been wondering: Why would you want to have the array index not to start with 0?

I guess it may be more familiar for beginners to have arrays starting with 1 and the last index being the size of the array, but on a long-term basis, programmers should get used to values starting with 0.

Another purpose I could think of: In some cases, the index could actually represent something thats contained in the respective array-entry. e.g., you want to get all capital letters in an array, it may be handy to have an index being the ASCII-Code of the respective letter. But its pretty easy just to subtract a constant value. In this example, you could (in C) simply do something like this do get all capital letters and access the letter with ascii-code 67:

#define ASCII_SHIFT 65
main()
{
    int capital_letters[26];
    int i;
    for (i=0; i<26; i++){
        capital_letters[i] = i+ASCII_SHIFT;
    }   
    printf("%c\n", capital_letters[67-ASCII_SHIFT]);
}

Also, I think you should use hash tables if you want to access entries by some sort of key.

Someone might retort: Why should the index always start with 0? Well, it's a hell of a lot simpler this way. You'll be faster when you just have to type one index when declaring an array. Also, you can always be sure that the first entry is array[0] and the last one is array[length_of_array-1]. It is also common that other data structures start with 0. e.g., if you read a binary file, you start with the 0th byte, not the first.

Now, why do some programming languages have this "feature" and why do some people ask how to achieve this in languages such as C/C++?, is there any situation where an array starting with a nonzero index is way more useful, or even, something simply cannot be done with an array starting at 0?

© Stack Overflow or respective owner

Related posts about arrays

Related posts about programming-languages