Re:Why do arrays start at 0?
by jbaczuk on Wednesday August 24, 2022 @05:49PM
(#32586229)
Yeah, but then couldn't the compiler just swap the 1 with a 0 and 256 with 255?
[ Parent
| on HN ]
That gets really dicey if you're storing the value of the index in a variable. Does the programmer need to know that if it's an INDEX they're storing that goes from 1-256 they can fit that into an 8-bit value because the compiler will magic away that last bit? Speaking of which, how will the compiler know which 1's are really 0's and which 256's are really 255's? Will it compile that 1+1=1 if I use that result as an index? Just having a 0th index is much simpler than all of that noise.
not really? It just changes how the compiler emits the x := *(addr + idx) operation where instead of doing something like
ldr x, [addr, idx]
it just does sub t1, idx, #1
ldr x, [addr, t1]
If we're talking about C, accessing invalid/OOB indices is undefined and so if idx happens to be zero and unsigned, we'll overflow and hit something unexpected, which is fine.That's what I was thinking too, except that they have a point. You might end up using more bytes to store indexes as variables (if the index is 256 for example), than you would with zero indexing.