When you try to access an element in a std::array
using an index that is out of bounds, the behavior is undefined.
In C++, arrays do not perform any bounds checking. This means that if you use the []
operator to access an element at an index that doesn't exist, the compiler won't stop you. Instead, it will happily let you access memory that doesn't belong to the array.
Here's an example:
#include <array>
int main() {
std::array<int, 3> MyArray{1, 2, 3};
int value = MyArray[10];
}
In this case, MyArray
only has 3 elements, so trying to access MyArray[10]
is out of bounds. This code has undefined behavior, which means anything could happen. Your program might crash, it might appear to work fine, or it might behave erratically.
However, most compilers will warn you about out-of-bounds access if you're running in debug mode. For example:
array subscript out of range
If you want bounds checking, you can use the at()
function instead of the []
 operator:
#include <array>
#include <iostream>
int main() {
std::array<int, 3> MyArray{1, 2, 3};
try {
int value = MyArray.at(10);
} catch (const std::out_of_range& e) {
std::cout << "Caught out_of_range: "
<< e.what() << '\n';
}
}
Caught out_of_range: invalid array<T, N> subscript
The at()
function will throw a std::out_of_range
exception if the index is out of bounds, which you can catch and handle.
However, the at()
function does come with a slight performance overhead due to the bounds checking. Therefore, it's generally best to ensure your indices are correct rather than relying on at()
.
Answers to questions are automatically generated and may not have been reviewed.
std::array
An introduction to static arrays using std::array
- an object that can store a collection of other objects