Re: Why do programmers start counting from 0?
Date: 9 Dec 2004 08:25:32 -0800
Starting at 0 for indexes makes for simpler pointer arithmatic.
Heres the simplest implementation for arrays in memory.
Say with an array A, consisting of elements each L bytes in size.
The members of A are indexed using a zero based index.
Within code the array can be represented as a pointer to the arrays base element (PB).
The calculation to find the memory address for A[I] is simply PB + (I * L).
If the index started at 1, it would be a little extra complexity. Either the pointer would have to be to the address PB-L, or the lookup would be PB + ((I - 1) * L).
It isn't much, but programmers will go to amazing lengths to spare a few bytes or a couple of clock cycles. It's a matter of professional pride. Received on Thu Dec 09 2004 - 17:25:32 CET