Thursday, December 08, 2005

A Random Thought!

Most of the general purpose languages like C, C++, Java start their array index from 0. Isn't it more natural to start from 1? Now the last index of the array is also the size of the array, thus avoiding subtraction of 1 to get to the last index. Also 0 could have been used to represent an invalid index in the array. What could have been the reason to start indexing from 0?

4 comments:

Niranjan Tulpule said...

I think it is because indexes are always viewed as offsets to the base address of the array. So the first element would start at the base address and second one a few bytes later and so on...

This seemed logical because before C, people were programming in assembly language and this was just a natural extension to them (Kernighan and Ritchie). C++ and Java just continued this tradition.

Anonymous said...

To add to what nanolucifer said, 'array index out of bound' checks etc were never there in the earlier languages.

Take a look at Matlab: one based indexing. I had a lot of trouble wrapping my head around that idea - what with my c/c++ background :-)

Venky (வெங்கி்) said...

I presume someone thought the same while developing C# [.NET framework's System.Array allows the lower bound to be something other than 0 too]. You can refer C# arrays.

Nirek said...

Thats an intriguing question! I was looking in the web for any different answer other than posted earlier.
this wiki entry looks nice
http://en.wikipedia.org/wiki/Array

There is always debate over one-based, zero based array. I will support One-based arrays, becos thats quite natural. You can implement any mathematical expression easily.