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?
-1
of a subarray is a perfectly valid way to refer to the element before that array in the larger array. The other is that if the index is invalid, the program is invalid, but in most implementations you'll get silent bad behavior, not an out-of-range error. $\endgroup$