As opposed to some other languages, C++ does not perform any runtime bounds checking as you have observed. The size of the array is not actually stored anywhere and not available at runtime. As such, at runtime no such checks can be performed. This was a conscious choice by the language creators to make the language as fast as possible while still being able to opt into bounds checking with the solutions I have outlined below.
Instead, what happens is known as undefined behaviour which C++ has a lot of. This must be always avoided as the outcome is not guaranteed and could be different every time you run the program. It might overwrite something else, it may crash, etc.
You have several solution paths here:
Most commonly you will want to use std::array
such that you can access its .size()
and then check for it before accessing:
if (i < arr.size())
arr[i] = value;
else // handle error
If you want to handle the error down the line you can use std::array
and its .at()
method which will throw a std::out_of_range
in case the index is out of bounds: https://en.cppreference.com/w/cpp/container/array/at
Example: http://coliru.stacked-crooked.com/a/b90cbd04ce68fac4 (make sure you are using C++ 17 to run the code in the example).
If you just need the bounds checking for debugging you can enable that option in your compiler, e.g., GCC STL bound checking (that also requires the use of std::array
)