2 ms·
if you see how its implemented in machine code (on most modern archs) you will see how it is logical. once you see that, you cannot unsee it. people call these
by sim7c00 2y ago
if you see how its implemented in machine code (on most modern archs) you will see how it is logical. once you see that, you cannot unsee it.
people call these things an index, but really it is an offset from the base of the array. not an index into it. hence, base + 0 is the first entry. as the offset to that entry is 0. thats how it will work in generated machine code on all the machines i saw (i did not see all of them obviously).
i think people struggle with these concepts because they never bother to see whats under the hood. a bit of assumption ofc on my part i cant see into ppls minds nor do i know all architectures. x86 and x64 (amd/intel) definitely work like this.
- InsideOutSanta 2y agoYes, it's the offset from a pointer in some languages. But to the user, it's presented as an index, not an offset. In normal syntax, you don't access an array value using a construct like *(arraypointer+offset) If you did that, then using 0 as the start offset would make intuitive sense. In fact, if not for this technical reason, I doubt that any programming language would have 0-based indices.
- sim7c00 2y agoim not debating the user level stuff. honestly i think there's fair argument for not letting users get bogged down in system level details. but in my opinion, if people dont understand this why, its a useful thing to learn. its only a small detail in the end. i think, because software is built up abstractions over abstractions, its unavoidable such details creep into languages from the depths of the system. its not too long ago people didnt even have C or such high level constructs. so coming from there and building up its logical. Now, making something new, from above, one might put 1 as an index for the first element, but its likely during writing of a language you'll end up in the depths and come up with 0 anyway. think of how a 1 index will work vs a 0 index on ptrs. (pseudo code) ptr += index x size_of_object ptr += (index-1) x size_of_object if you wanna run that on the cpu, either compiler needs to come up with the first one or it will have an additional sub or decrement? or do you want the compiler to have a duty of doing the index-1, it will result in the original code again, also possible. it will take extra compiler or interpreter time. (or am i missing something completely?)
- InsideOutSanta 2y agoI don't disagree with anything you say. I'm not saying that C should have 1-based indices, for example. I'm only saying that from a language design perspective, ignoring technical limitations and historical precedents, 1-based indices would be preferable.
- School-Cotton 2y ago0 is logically superior regardless of how any of it is implemented under the hood. It just makes more sense.