Edsger Dijkstra explains why array indexes should start at 0 rather than 1. [pdf]
Here’s the summary: first, let’s consider question of how to represent a range of natural numbers. For example, consider the range of integers . There are four compact ways to represent this by varying whether we use or :
Which is best? In the last two variants, we can subtract the first number from the last to find the size of the range. Based on that favorable property, let’s restrict our options to those two.
What if we instead wish to represent ? Our two candidates give us:
The second representation forces us into the realm of unnatural numbers, which is not ideal. So we have our winning representation: .
Let’s return to the original problem of indexing things. We have two choices for representing the entire range, depending on whether we start at or :
Indexing starting at requires a clumsy ; starting at allows us to write the number of elements directly as part of the range. We conclude that indexing starting at 0 allows us the greatest notational convenience.
Which is best? In the last two variants, we can subtract the last number from the first to find the size of the range. Based on that favorable property, let’s restrict our options to those two.
This is something I do not agree with. Some languages (eg. Lua) use the 2nd variant, and there is no reason to dismiss it just because you cannot substract the last number from the first to find the size of the range. Indeed, it gives you another interesting property: if your range starts with 1, then the last number is the size of the range.
The result is that when you iterate over a whole array, instead of writing (like in c):
for(i=0,i<n,++i) { puts(array[i]); }you write:
for i=1,n do print(array[i]) endwhich is equally readable to me.
Including both ends is also how most mathematicians usually represent an integer range ({5,6,7} is [[5,7]]) and how we describe them in spoken language (“integers from 5 to 7”). And most importantly, array(3) is the third value in the array, not the fourth. I think this is much more disturbing than the fact that there are 7-5+1 integers in {5,6,7}.
Actually readable version of this comment available here: http://1based.pen.io/
[Fixed. —ed.]
Hi,
Sorry for the top-posting, but I wanted to let you know that your rss feed (and it appears your email reply thingy) doesn’t escape things (or unescape them?) like you might want. This article demonstrates that.
I enjoy your blog. Have a nice day.
-Sam
[Excessively-large quote automatically elided. — ed.]
I think I’ve fixed this. Math (on the web) is hard.
When I pull up your RSS feed I still see the backslashed "le"s etc.
When I pull up your RSS feed I still see the backslashed "le"s etc.
Oh, that. Yeah, there’s no good way to do that. Text and RSS versions will have the original LaTeX-style math notation; only the HTML view can turn it into pretty math.
And even that was incredibly difficult to get working.