If I had already declared the size and initialize the array in this C++ snippet how is this code running?

  c++

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 :-

  1. If array size was fixed to 10 items how come I was able to add a value at the index number 15 ?

  2. If arrays are contiguous blocks of assigned memory , then how come I was able to jump out and declare a value skipping indices?

  3. From where do the output of values at index numbers 11 and 12 come from ?

  4. Does that mean C++ does not check ArrayOutOfIndex errors like Java and Python ?

  5. 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.

Source: Windows Questions C++

LEAVE A COMMENT