|
|
|
|
|
by umanwizard
552 days ago
|
|
I have a really hard time understanding why people like 1-based indexes! 0 is the smallest unsigned integer in every programming language I know of that supports the concept of unsigned integer. Why shouldn’t an array at the smallest possible index correspond to the beginning of the array? It’s also very natural to think of arr[i] as “i steps past the beginning of arr”. With one-based indexing arr[i] has no natural interpretation that I know of. It’s “i-1 (for some reason) steps past the beginning of arr”. The only reason I can think of to prefer that extra -1 in your formula is just because human languages (at least the ones I know of) work this way — the 42nd element of a sequence, in normal colloquial English, means the one 41 steps past the beginning. But I’m not sure if there is any logical justification for that. I also, despite being American, find the convention used in many countries of numbering building floors starting with zero to be more logical. I’m on the third floor, how many stories up did I travel to get here? Three. |
|
Because then there is no good way to refer to the index before that point: You are stuck using -1 (which means you can't use it to refer to the end of the array), or null (which isn't great either).
> every programming language I know of that supports the concept of unsigned integer
Surely you know Python which uses a signed integer as an index into their arrays: list[-1] is the last element of a list. If they only used one-based indexing then list[1] would be the first and that would be nicely symmetrical. It would also mean that list[i-1] would NEVER refer to a value after ‹i› eliminating a whole class of bugs.
> It’s also very natural to think of arr[i] as “i steps past the beginning of arr.”
I think it's more natural to think of arr[i] as “the ‹i›th element of arr” because it doesn't require explaining what a step is or what the beginning is.
The exact value of ‹i› matters very little until you try to manipulate it: Starting array indexes at one and using signed indexes instead of unsigned means less manipulation overall.
> find the convention used in many countries of numbering building floors starting with zero to be more logical
In Europe, we typically mark the ground-floor as floor-zero, but there are often floors below it just as there are often floors above it, so the floors might be numbered "from" -2 for example in a building with two below-ground floors. None of this has anything to do with arrays, it's just using things like "LG" or "B" for "lower ground" or "basement" don't translate very well to the many different languages used in Europe.
The software in the elevator absolutely doesn't "start" its array of sense-switches in the middle (at zero).