C++ Basics: Check Fixed-Array Access with at
Use std::array::at when an index should be checked and an out-of-range access handled explicitly.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as array-at-bounds-exception-demo.cpp:
#include <array>
#include <cstddef>
#include <iostream>
#include <stdexcept>
int main()
{
const std::array<int, 3> samples{10, 20, 30};
for (std::size_t index : {std::size_t{2}, std::size_t{3}}) {
try {
const int value = samples.at(index);
std::cout << index << ": " << value << '\n';
} catch (const std::out_of_range&) {
std::cout << index << ": out of range\n";
}
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic array-at-bounds-exception-demo.cpp -o array-at-bounds-exception-demo &&
./array-at-bounds-exception-demoObserved output:
2: 30
3: out of rangeRead the result
Index two selects the third element. Index three equals the size, so at() throws and the catch block prints a predictable message. Reading the value before printing the line avoids leaving a partial success message.
Apply it carefully
Valid indices run from zero through size minus one. Use explicit validation when invalid input is an expected part of normal control flow. Do not rely on operator[] to throw. Exception what() text varies by implementation; this example deliberately prints its own message.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- array-at-bounds-exception-demo.cpp array-at-bounds-exception-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.