Advantages of initial arrays at 0?

What is the purpose of array indices, starting at 0 in most programming languages, as opposed to the ordinal method in which we refer to most IRL things (first, second, third, etc.)? What is the logic or usefulness of this?

I’m already used to it, but I never thought about the reason for this.

Refresh . One of the advantages that I read from Googling is that there can be i < n for loops if you want to go to n .

+4
source share
6 answers

Dijkstra discusses why numbering should start from scratch .

When considering a sequence of length N whose elements we want to distinguish by indexes, the next annoying question is what index value should be assigned to its original element ...

when starting with index 1, the range of indices is 1 ≀ i <N + 1; starting from 0, however, it gives a better range 0 ≀ i <N. So, let our ordinals start from zero: the serial number of the element (index) is equal to the number of elements preceding it in the sequence. And the moral of this story is that we were better at it after all these centuries! - zero as the most natural number.

+9
source

Dijkstra wrote a very interesting article about this, in 1982: Why numbering should start from scratch .

+2
source

When we access an element by index, for example [i], the compiler converts it to [a + i]. Thus, the index of the first element is zero because [a + 0] will give us "a", which points to the first element in the array. This is quite obvious, for example, for C ++, but not for later languages ​​such as C #.

+2
source

You can use Google for this, there have been many discussions. I would say that the fact that the offset of the first element from the very beginning (which it is) is zero, of course, makes sense.

0
source
0
source

In my old days of assembler, it was natural for the offset to start from scratch.

 dcl foo(9) ldx0 0 'offset to index register 0 lda foo,x0 'get first element adx0 1,du 'get 2nd ldq foo,x0 

When looking at it in terms of hardware, it makes sense.

0
source

Source: https://habr.com/ru/post/1386595/


All Articles