Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of starting arrays at 0?

What's the purpose of array indices starting at 0 in most programming languages, in contrast to the ordinal way in which we refer to most things IRL (first, second, third, etc.)? What's the logic or utility behind that?

I'm completely used to it by now, but never stopped to think about the reason behind it.

Update: One benefit I read about from Googling is that for loops can have i < n if you want to go up to n.

like image 907
bgcode Avatar asked Dec 16 '22 06:12

bgcode


2 Answers

Dijkstra lays out the reasoning in Why numbering should start at zero.

When dealing with a sequence of length N, the elements of which we wish to distinguish by subscript, the next vexing question is what subscript value to assign to its starting element...

when starting with subscript 1, the subscript range 1 ≤ i < N+1; starting with 0, however, gives the nicer range 0 ≤ i < N. So let us let our ordinals start at zero: an element's ordinal (subscript) equals the number of elements preceding it in the sequence. And the moral of the story is that we had better regard —after all those centuries!— zero as a most natural number.

like image 98
Bill the Lizard Avatar answered Jan 06 '23 11:01

Bill the Lizard


When we're accessing item by index like a[i] the compiler converts it to [a+i]. So the index of first element is zero because [a+0] will give us 'a' that points to the first item in array. This is quite obviously for, say, C++ but not for more recent languages such as C#.

like image 27
mayor Avatar answered Jan 06 '23 10:01

mayor