I set 2 places in array called a .
despite i put for loop exceeds than my array, it works correctly and give me the answer of a[5] correct !! how does array work in this situation?
then why i put a[2] even it will work for 5??
1 2 3 4 5 6 7 8
void main ()
{
int a[2];
for (int i =0; i<=5;i++)
cin>>a[i];
cout<<a[5];
}
If you assign more values in your array than its size, it will generate "undefined" behavior.
In your simple case, it seems that you can still print out a[5] as desired since you are not exceeding the array size too much. However, when you try the following, the program will crash.
1 2 3 4 5
constint NUMBER = 500; // exceeds the size of the array too much
int a[2];
for (int i = 0; i < NUMBER ; i++)
a[i] = i;
cout << a[NUMBER];