Interview Question
Country: United States
In C and C++ yes, it is allowed.
In java you will get 'ArrayIndexOutOfBoundsException'.
You can easily mess around with addresses in C. That is both the beauty and the drawback of using C language.
Now try predicting the output of this question:
#include<stdio.h>
int main()
{
int a[3],i;
for(i=-1;i<3;i++)
{
// printf("i is %d\n",i);
a[i]=-2;
// printf("i is %d\n",i);
}
}
This gives you an infinite loop because a[-1] points to i
a[i]=-2 means i=-2.
Then i++ changes i to -1
and it gets stuck in an infinite loop!
Due to these security issues is C, there came the arrival of a new programming language- Java, which is nothing but modified C++ to remove security vulnerabilities and have better checks for overflows,etc.
a[-1] points to i because when the line
int a[3],i;
is encountered during execution, space is allocated in stack equal to space of 3 ints (for array a) + space for 1 integer (ie i). Let the adress of a[0] be 0x00000008 (for simplification and assuming 32 bit int size). Then a[1] would be at address 0x0000000c and a[2] would have address 0x000000010. The address of i would be 4 bytes before a[0]'s address in stack ie 0x00000006 because the space is allocated in Right To Left order ie i first, followed by a[3].