CKTIS / C++
Array subscript operator []
The [] operator selects an array element or an element relative to a pointer. Array indices start at zero, and the built-in operator does not check bounds. Classes can define their own operator[], whose behavior depends on its implementation.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
array_or_pointer[index]
object[index]
object[row, column] // C++23: requires a matching overloaded operator[]The [] operator performs subscripting: values[i] denotes the element of array values at index i. For an array of n elements, valid element-access indices are 0–n - 1. The built-in operator takes an array or pointer and one index of integral or unscoped enumeration type.
Built-in E1[E2] corresponds to *((E1) + (E2)), with a value-category qualification for array operands: the result is an lvalue for an lvalue array and an xvalue otherwise. For an ordinary named array or pointer, the result designates an element and can be assigned to if that element is modifiable. Thus, values[1] = 25 changes the second element, and p[1] also works when pointer p points to the first element.
Built-in [] does not check bounds. Reading or writing outside the array causes undefined behavior. A pointer just past the end may serve as a boundary, but must not be used to read or write an element. A negative index relative to the first element is also invalid.
A class can define a member function operator[]; its return type, index meaning, and bounds checking depend on that function. In C++23 an overloaded operator can accept multiple arguments, for example object[row, column]. This does not change built-in arrays: their operator requires one index, and an array of arrays is indexed as matrix[row][column]. The supplied source is an evolving standard draft, not a frozen C++23 publication.
Examples
#include <iostream>
int main() {
int values[] = {10, 20, 30};
values[1] = 25;
int* p = values;
std::cout << values[0] << ' ' << p[1] << ' ' << values[2] << '\n';
}
Result
10 25 30
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.