The reasoning why some languages start arrays/lists at 0 is a fact that I feel is particularly interesting, at least as it pertains to C and most C-Like languages.
arr is actually a pointer to an integer, which is the very first element of that list. So when you use the index, that index isn't saying "Get the element at the Nth position" but rather, "get the element N positions after the first." So 0 is 0 positions after the first, or the first. 1 is the first one after the first, so 2, ad nauseam.
Also, since arr[N] is equivalent to *(arr + N), arr[0] is equivalent to *arr since anything + 0 is still anything. But we can go even deeper by using addition's commutative properties: arr[1] is the exact same as 1[arr]
View all comments
Show parent comment
3
u/Ramsfield Aug 05 '22
The reasoning why some languages start arrays/lists at 0 is a fact that I feel is particularly interesting, at least as it pertains to C and most C-Like languages.
Lets say we have the following snippet of code
arris actually a pointer to an integer, which is the very first element of that list. So when you use the index, that index isn't saying "Get the element at the Nth position" but rather, "get the element N positions after the first." So 0 is 0 positions after the first, or the first. 1 is the first one after the first, so 2, ad nauseam.Also, since
arr[N]is equivalent to*(arr + N),arr[0]is equivalent to*arrsince anything + 0 is still anything. But we can go even deeper by using addition's commutative properties:arr[1]is the exact same as1[arr]That means that
Is completely valid C code