0
int a[10];
std::cin >> a[12];
std::cout << a[12];

Shouldn't the a[12] line raise an error as the array is only declared for 10 indexes? Is there something obvious I'm missing, or has it always been like this?

1 Answers1

3

You are free to index out of range, but it is undefined behavior. This could eventually manifest in memory stomping, a write access error, or other.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • So is there a way to restrict input if index is more that that declared, without manually checking if the index location is more than the max defined index? – Mayur Mohan Aug 17 '14 at 14:13
  • @MayurMohan, Use `std::array` and its `at` member function, or check the index against the size if you actually plan on it going over sometime. – chris Aug 17 '14 at 14:14