Monday, 22 June 2020

Why indexing in array starts with 0 ?

Array Index starts with zero

In most common programming languages, the indexing in array starts with zero (0). The reasons behind this are:

In programming languages like C and C++, the array name refers to the location in the memory which means the array name simply points to first element of the array and array[n] refers to the location of n-elements away from the first element. Here, n is used as an offset from the array’s first element. So the first element is at zero (0) distance away from the array. That’s why array index starts with zero.

Performance overhead:

Zero (0)-based index allows array[n] to be implemented as *(array + n). If index were one (1)-based, compiler would need to generate *(array + n - 1), and this "-1" has some performance overhead. As this extra subtraction instruction lowers the performance to low extent but this adds up to a lot when one has to write for the Compiler.  

And the common programming languages developed after C and C++ follows the same design logic for the indexing of the array.

Here is the proof:

#include <stdio.h>

int main()
    int array[5] = {1, 2, 3, 4, 5};
    printf( "Array location: %p\n", array );

   printf( "Array location of first element: %p\n", array[0] );




Array location: 0x7ffde4bf25b0
Array location of first element: 0x7ffde4bf25b0


See the output above, both array and array[0] refers to the same memory location.