Why do negative array indices make sense?

  • A+
Category:Languages

I have came across a weird experience in C programming. Consider this code:

int main(){   int array1[6] = {0, 1, 2, 3, 4, 5};   int array2[6] = {6, 7, 8, 9, 10, 11};    printf("%d/n", array1[-1]);   return 0; } 

When I compile and run this, I don't get any errors or warnings. As my lecturer said, the array index -1 accesses another variable. I'm still confused, why on earth does a programming language have this capability? I mean, why allow negative array indices?

 


Because that's just pointer arithmetic.

In fact,

int array[] = {1, 2, 3, 4, 5, 6}; 

then you can write expressions like

int *pointer = array - 1; 

and that's just array[-1].

Now, the fact that this is possible doesn't mean it's correct. The expression above is undefined behavior because you are going out of the array bounds.

Nontheless it's valid if

int *ahead = array + 3; int third = ahead[-1]; 

here third will have the value of array[2] so 3.

To answer this

As my lecturer said, the array index -1 accesses another variable. I'm still confused, why on earth does a programming language have this capability? I mean, why allow negative array indices?

I would say that it's not true that index -1 refers to another variable. You can't really know what does the index -1 refer to and it will be specific to a given program.

In general you can't predict what the resulting "thing" is pointing to or what value will be read at that location, hence, the term Undefined Behavior.

It's also not possible to predict the behavior of subsequently accessing or using such a value or pointer.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: