why does the array index (for counting elements) start from 0(zero)?
answer me please.... I'm a new user
why does the array index (for counting elements) start from 0(zero)?
answer me please.... I'm a new user
It makes for easier indexing into the array with pointer arithmetic. Many languages start their indexing at 0, and some start at 1 - it was the language designer's decision on what to start with.
Mainframe assembler programmer by trade. C coder when I can.
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge
The technical reason is that C is supposed to be an efficient language. If we have a chunk of memory (which is what our array is) that starts at address 1000, the first element of that is at address 1000, right?
So, if we have indices starting at 1, the compiler would have to subtract one before it can find the actual memory address of the element we request, the calculation of a particular element is: baseaddress + ((index-1) * sizeof(element)). In the case of 0-based indices, there is no need to subtract anything, because baseaddress + (index * sizeof(element)) gives us the appropriate address.
The 0-based index is thus a better solution for efficiency. It may not suit human beings quite as well as a 1-base index, but C was never intended to be "human efficient", but definitely the goal is to be "machine efficient".
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
After using C++ for so long, it seems strange to me when I use languages that start their indexes at 1.
"I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008
"the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010
Because if a[] is an array then a is a pointer to the first element; and a[n] is the same as *(a+n); therefore a[0] is the same as *(a+0) which is the same as *a which is the same as the value of the first element of the array, therefore a[0] must be the first element of the array. It all follows from the basic definitions.
Code://try //{ if (a) do { f( b); } while(1); else do { f(!b); } while(1); //}