Why don't programming languages allow for negative array indexes?
Sure I understand I'm guessing it has to do with the underlying c code about basically moving forwards by a block of memory equal to the datatype's sizeof value from the first element onwards.
But from a mentally logical way of thinking about it - allowing indexes that used the full signed integer range to access them would allow for some interesting programming features.
This is just thinking out loud though, and I'm sure there's a million and one practical reasons why it simply doesn't exist.
I'm guessing it's just the way it maps it along with memory... Though thinking about it, I have seen something similar with strings, which is essentially an array of characters, but all it did was loop back on itself, so if you put -1 as an index, you'd be at the character at the end of the string.
P-code:
local str:string = "hello"
print str[-1]
Output: o
Dabz
What would be a use case for negative indices?
The question is never "why" but "how":
Global MyArray:Negative = New Negative(1000)
MyArray.Set -111, 5
Print MyArray.Get(-111)
Type Negative
Field array:Int[], DimHalf:Int
Method New(Dimension:Int)
array = New Int[Dimension]
DimHalf = Dimension/2
End Method
Method Set(Element:Int, Value:Int)
array[Element+DimHalf] = Value
End Method
Method Get:Int(Element:Int)
Return array[Element+DimHalf]
End Method
End Type
A use case: imagine a 2d array for a world map where each index refers to an X or z co-ordinate. Typically you adjust the world position before putting into the array to avoid going out of bounds. But if negative indexes were allowed it would mean you wouldn't need to adjust the coords before putting into the array.
That's why other data structures to arrays were invented - because they can be more flexible.
I get the idea, but it seems very limited use really.
You could simulate this just by having some offset to references of the positivie integer elements.
The 'reason' behind having a zero or 1 initiated positive count is ( I believe, may not be the actual reason ) due to the array representing a structured count of items. Any such list will always be positive -
Similar to measuirng a distance. You can have a negative quantity in terms of vector direction, but the magnitude will always be positive since it is "number of steps taken" -
How can you traverse an array if you don't know ehere to start?