4 ms·
I always found array index confusing. For example, given a array with size N in Python, we can iterate it from 0 to N-1 (onwards) and from -1 to -N (backwards)
by maxloh 3y ago
I always found array index confusing.
For example, given a array with size N in Python, we can iterate it from 0 to N-1 (onwards) and from -1 to -N (backwards), which is not consistent at all.
Programming language is meant for human eyes. It would be better if array index being 1 to N, and let the compiler substract that 1 for us.
- bakuninsbart 3y agoObviously comes from a time when you were either not using a compiler, or you were writing a compiler. Compared to many other foundational oddities in software engineering this is a really minor one, and at this point it is impossible to change. Any new language starting arrays at index 1 would feel unattractive to me.
- DuckFeathers 3y ago[dead]
- KnobbleMcKnees 3y agoThis is surely an inconsistency with Python, not with array indexing at large.
- afiori 3y ago0 = -N mod N and N-1 = -1 mod N The consistency is that if i < 0 and l[i] exists then l[i] = l[i+N]
- abdullahkhalids 3y agoOne idea is a programming language that allows both, with different syntax. Say A[i] for 0 based and A{i} for 1 based.
- majewsky 3y agoThis sounds like a really good idea... if you want to hide subtle backdoors in innocuous-looking code.
- abdullahkhalids 3y agoIt would be okay for scientific programming languages like Mathematica or Matlab which are usually not used within adversarial security scenarios.
- mixmastamyk 3y ago1-based indexing has confusing aspects as well when manipulating memory locations. 0-based is slightly less confusing over all, and why it is used more often in programming.
- nullindividual 3y agoVB.NET starts indexing at 1 if you want a dead language as an example.