Hacker News new | past | comments | ask | show | jobs | submit login

I never found it to be a big deal, unless you're trying to copy algorithms from another language nearly verbatim. There's not really any math that relies on 0 indexing,



I guess it depends on what you mean by "relies"

Using a single dimensional array as a 2 dimensional array relies on zero indexing.

    index = y * width + x
    array[index]
Using modulo to covert an index back to 2 dimensions relies on 0 indexing

    x = index % width
    y = index / width
Skipping a prefix in a string.

    prefix = "ABC"
    string = "ABCdef"
    unprefixed = string[prefix.length:]
    
I'm sure there are tons of others. Yes, you can add 1 or subtract 1 in the right places. That's the annoying part of it though.


Eh, for every use case where it's more convenient that arrays start at zero, there's one where it's more convenient that arrays start at one, and vice versa.

For example, to get a prefix of length 'n', you need characters 0 through n-1 with zero-based indexing and 1 through n with one-based indexing. (That Python hides the -1 when using a [0:n] range is a convenience; the subtraction still happens internally.)

Similarly, to get the last element of a one-based array with a[length(a)] and the last element of a zero-based array with a[length(a)-1].

What it comes down to is that sometimes you have to write +1 or -1 for zero-based indexing where you can avoid it for one-based indexing and vice versa. What is not the case is that it only universally happens for one of those schemes.


Good points. I was thinking that there are probably an equal number of array arrithmatic tricks that also require a +-1 here and there, but it was just a hunch. As I said though, never found it to be a problem in practice.


The first two examples already work in lua if you just put something at 0.


Well lua doesn't even have an operator for integer division.


Mathematically, starting with zero is more consistent, because it leads to the fact that the length of a range is the difference between its bounds (length x..y == y-x).

More elaborate and rigorous: http://www.cs.utexas.edu/~EWD/transcriptions/EWD08xx/EWD831....




Consider applying for YC's Summer 2025 batch! Applications are open till May 13

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: