Out-of-Bounds Array Access

What happens if I try to access an element in a std::array using an index that is out of bounds?

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().

Static Arrays using std::array

An introduction to static arrays using std::array - an object that can store a collection of other objects

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Array Initialization
What are the different ways to initialize a std::array in C++?
Passing Arrays by Reference
Why is it more efficient to pass a std::array by reference to a function instead of by value?
Changing Array Size
Can I change the size of a std::array after it has been created?
std::array vs C-style Arrays
What are the advantages of using std::array over traditional C-style arrays?
Accessing Elements in Nested Arrays
How do I access elements in a multidimensional std::array?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant