Static Arrays using std::array

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?

Abstract art representing computer programming

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved