ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button
Article:
  What I Hate About Your Programming Language
Subject:   C, C++, Java, maybe others - zeroth element arrays
Date:   2003-05-15 01:41:27
From:   anonymous2
Response to: C, C++, Java, maybe others - zeroth element arrays

I know that others breifly mentioned why the zero is used, but clearly a better explanation is needed to enlighten those that think that it should start at 1. An array is an address. It is not some magic black box that has numbers. The address points to the first element of the block of memory that is the array. So lets say we have 'int array[10];'. 'array' is the same address as 'array[0]'. So the point is that you are asking how much should be add to the address to get to the first element. Add nothing (zero). Now lets say that we had compiler that did the index beginning at 1. If we explicitely said 'array[1]' this could be easily coded in assembly to access with a 0 offset, but what if we had 'array[i]'. The assembly must access the value of i and then subtract one. This adds an extra instruction that is otherwise not necessary. Clearly you know nothing about pointer or else it would be obvious about the arbitrary choice between using one or another. If I say 'int * ptr; ptr = array;', I can say '*(ptr + n)' to mean 'array[n]'; Is it clear now why this is the way it is. You clearly don't program in C much and don't know about the underworkings of the architecture.