The Arrays in most programming languages(C, C++, Java, Python) start with index 0 instead of 1. While it may seem counterintuitive, but using zero-based indexing offers unexpected advantages for both compilers and programmers.
Recall the instance when you were introduced to the C programming language and were told that arrays in C start with index zero. I bet you wondered why 0! π€ Wouldn't be 1 a more obvious choice.
The Arrays in most programming languages(C, C++, Java, Python) start with index 0 instead of 1 and there are some surprising benefits of zero-based indexing for both compilers and programmers π.
Faster Compilation
In C, The name of an array is essentially a pointer to the starting address of contiguous memory allocated. Consider an array with starting address as 0x400.
int arr[5];
In Zero Based Indexing
To access the first element in array, arr[0] must be computed as *(arr + 0). Similarly, To access ith element in array, arr[i] must be computed as *(arr + i * sizeof(int)). It takes compiler 2 add operations to compute the address of ith element.
In One Based Indexing
The first element in array, arr[1] must be computed as *(arr + 1 - 1). Similarly,ith element in array, arr[i] must be computed as *(arr + (i - 1) * sizeof(int)). It takes compiler 3 add operation to compute the address of ith element.
Hence, It is efficient for the compiler to implement zero-based indexing βοΈ.
Now, How many operations does it take to compute the address of arr[i][j]? I will leave it to you as an exercise βΊοΈ, please respond in the comment section.
π‘
Remember, C compiler uses Row Major to compute memory address.
Programmer's Ease
Don't Miss an Update!
Helping you navigate the Embedded Systems career with ease! Technical posts, newsletters, special offers, and more.