3 ms·
"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration." — Stan Kelly-Bootle
by pansa2 2y ago
"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration." — Stan Kelly-Bootle
- kps 2y agoFirst person to get a postgraduate degree in CS. I still miss his satirical writing.
- TOGoS 2y agoHe was right. If the first fencepost is centered at x=0 and the second at x=1, and you want to give the rail in-between some identifier that corresponds to its position (as opposed to giviung it a UUID or calling it "Sam" or something), 0.5 makes perfect sense. In computer programming we often only need the position of the gap to the left, though, so calling it "the rail that starts at x=0" works. Calling it "the rail that ends at x=1" is alright, I guess, if that's what you really want, but leads to more minus ones when you have to sum collections of things.
- edbaskerville 2y agoI can't find a reference, but I have a vague memory that in original Mac OS X, 1-pixel-width lines drawn at integer locations would be blurred by antialiasing because they were "between" pixels, but lines drawn at e.g. x = 35.5 were sharp, single-pixel lines. Can anyone confirm/refute this?
- TOGoS 2y agoNot sure about old Mac OS, but I think HTML canvas works that way.
- boothby 2y agoPython supports a third way: start at -1. And if you think about it a little (but not too much) then there's some real appeal to it in C. If you allocate an array of length n and store its length and rewrite the pointer with (*a+=n)=n, then a[0] is the length, a[-1] is the first element (etc) and you free(a-a[0]) when you're done. As a nice side effect, certain tracing garbage collectors will never touch arrays stored in this manner. Upshot: if you take the above seriously (proposed by Kelly Boothby), the median proposed by Kelly-Bootle returns to the only sensible choice: zero.