|
|
|
|
|
by fpoling
420 days ago
|
|
I always thought that 0-based indexes were superior until few years ago I needed to deal with Fortran code and I realized that 1-based arrays allowed to use 0 as a non-existing index or sentinel, not size_t(-1) hack as found in C/C++. Like the article explains, depending on the domain one or the other convention can be advantageous. And then C/C++ compilers are subtly inconsistent. If 0 is valid index, then null should correspond to uintptr_t(-1), not 0 address. That lead to non-trivial complication in OS implementations to make sure that the address 0 is not mapped as from hardware point of view 0 is absolutely normal address. |
|
In the same way we index from 0 because indexing gets way more awkward if we index from 1.
In-band sentinels are both quite rare, and also equally convenient with -1 or 0. In fact I would say -1 is a bit more elegant because sometimes you need multiple sentinel values and then you can easily use -2 (what are you going to use 0 and 1 and then index from 2?).
The more common operations are things like indexing into flattened multidimensional arrays, or dealing with intervals, which are both way more elegant with 0-based indexing.
0 is a valid index into an array. It's even a valid index into global memory in some environments. Not mapping memory to address 0 is completely trivial. I'm not sure what non-trivial complications you're thinking of.