Search code examples
c++increment

Getting Unexpected value


I was playing around with array and when i did this , im expecting IndexOutOfBound
however , the program still ran and gave an output 54

Where does the extra number come from ?
How to avoid these kind of indexing problem?

#include <iostream>
int main(){
    int array[] = {1,2,3,4,5,6};
    int total;
    for(int i = 0 ; i<=7 ; i++){
        total += array[i];      
    }
    std::cout << total;
    return 0;
}

Solution

  • C++ does not do any checking to make sure that your indices are valid for the length of your array. Like churill notes above, indexing out of range is undefined behavior. For example, in your question, the value of array[6] is whatever is stored your memory at the location where the 6th element would have existed. In your case, this was a random value for instance from another variable.

    Although rare, C++ will also let you use a negative index, with similarly undesirable results.