I attended my class of c++ last day and teacher told me that references must refer to valid memory while pointer may or may not. I was playing with references and suddenly this question came in my mind. When i declare a array_demo of size 10 and assign it values to 10 to 19 why the program is compiling and i'm getting a garbage number if i'm referring something outside array (index 11) which is not a valid memory !
#include <iostream>
using namespace std;
int main()
{
int array_demo[10];
int x= 10;
for(int i=0; i<10; i++)
{
array_demo[i]= x; //assigning values to array_demo
x++;
}
for(int j=0; j<10; j++)
{
cout<<array_demo[j]<<endl; //printing array values
}
cout<<endl;
cout<<endl;
int *p_x=array_demo;
int &ref_x= array_demo[11];
cout<< *(p_x+11)<< endl;
cout << ref_x << endl;
}