I am new to C++(please assume no C knowledge while answering). I have just started learning about arrays and ran the following code :-
#include<iostream>
using namespace std;
int main(){
int arr_[10] ={1,2,3,4,5,6,7,8,9,0};
int i=0;
while (i<4)
{
printf("Value of arr_[ %i ] = %i \n",i ,arr_[i]);
i++;
}
arr_[15] = 555;
cout<<arr_[11]<<endl<<arr_[12]<<endl<<arr_[15];
return 0;
}
I was expecting an error but to my surprise the program successfully compiled and ran to produce the following output :-
Value of arr_[ 0 ] = 648017456
Value of arr_[ 1 ] = 648017456
Value of arr_[ 2 ] = 648017456
Value of arr_[ 3 ] = 648017456
4
1
555
I tried the same program once again on another machine . It produced a different output:-
Value of arr_[ 0 ] = 1
Value of arr_[ 1 ] = 2
Value of arr_[ 2 ] = 3
Value of arr_[ 3 ] = 4
-1644508256
0
555
So here are my queries I want to resolve :-
If array size was fixed to 10 items how come I was able to add a value at the index number 15 ?
If arrays are contiguous blocks of assigned memory , then how come I was able to jump out and declare a value skipping indices?
From where do the output of values at index numbers 11 and 12 come from ?
Does that mean C++ does not check
ArrayOutOfIndex
errors like Java and Python ?I later added following line to my code :-
cout<<endl<<sizeof(arr_)/sizeof(int); //to find number of items
which returned the number of Items in the array to be
10
. And this makes me horribly confused . I tried checking in books but could not find relevant information or the terminology is too verbose to understand as a beginner and on web hunting for such information proved to be too painful and went into vain.