← Back to context

Comment by teddyh

1 year ago

Here’s the ultimate authority on why computer languages should count from zero:

<https://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF>

I find that argument to be written in a terse "mathy" style that makes it a bit hard to follow. So let me try to restate it in more concrete "programmy" terms.

To iterate over an array with "len" elements, it’s most elegant if “len” appears as a loop bound, rather than "len+1" or "len-1". Thus, in 0-based languages we use half-open ranges, whereas in 1-based languages we use closed ranges:

  // real C
  for (int i = 0; i < len; ++i)
      process(array[i]);


  // C-like language with 1-based indexing
  for (int i = 1; i <= len; ++i)
      process(array[i]);

But the second is inelegant when len is zero, because 0 isn’t a valid index at all, so it’s weird for it to appear as a bound.

Yeah, I disagree with Dijkstra on this. And many other things.

  • Dijkstra, being one of a handful of luminaries in the field of computer science – indeed, he can be said to have created the field itself – can be (provisionally) taken at his word when he claims something. You, on the other hand, being an anonymous user on a discussion forum, will have to present some pretty strong arguments for the rest of us to take you seriously. Your mere disagreement counts for approximately nothing.