0

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;
}
Amirul Akmal
  • 401
  • 6
  • 13
  • Why do you expect `IndexOutOfBound`? Can you point out a document that mentions this should happen? Writing (and reading) out of bounds is undefined behaviour in C++. Let me search some related questions. – Lukas-T Nov 12 '20 at 06:27
  • 1
    Does this answer your question? [Accessing an array out of bounds gives no error, why?](https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why) – Lukas-T Nov 12 '20 at 06:28
  • Also `total` is uninitialized. So even if you fix the for loop to just access: `for (int i = 0; i < 6; i++)`, then you still need to initialize `total = 0;` before the loop runs. – selbie Nov 12 '20 at 06:32
  • @churill i'm from python..trying different languages to find the suitable with me..after build several projescts on python..i were thinking to C/C++...as you may know , index in python will give `list index out of range` – Amirul Akmal Nov 12 '20 at 06:36
  • @churill the post really explained whole bunch of the `not giving error` , but still dont answer question `extra number come from?`..anyway good comment and thanks – Amirul Akmal Nov 12 '20 at 06:38
  • 2
    @prokillerinminecraft Because this is undefined behaviour C++ says nothing about where the extra number comes from. If you want an answer you have to look at your compiler and your operating system, it's not a C++ question. – john Nov 12 '20 at 06:52

1 Answers1

0

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.

Ladybug
  • 48
  • 8