Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

Array subscript operator []

The [] operator designates an element using an array or pointer and an integer index. Indexing starts at zero; the programmer must keep accesses within bounds.

Version: C23; repository compiler flag, production runtime not attested

Syntax

E1[E2] /* equivalent to *((E1) + (E2)) */

E1[E2] means *((E1) + (E2)). One operand must be a pointer to a complete object type, the other an integer. An array usually converts to a pointer to its first element. Offsets count elements, not bytes.

For an array a of N elements, accessible indices are 0 through N - 1. C requires no bounds checking: out-of-bounds reads or writes have undefined behavior. A one-past pointer may be formed but not dereferenced. A negative index is valid when it still designates an element of the same array.

a[i] can be assigned to if the element is modifiable. a[i][j] successively selects elements of nested arrays. Brackets in the declaration int a[3] declare an array rather than perform subscripting.

Examples

#include <stdio.h>

int main(void)
{
    int values[] = {10, 20, 30};
    int *p = values + 1;

    values[1] = 25;
    printf("%d %d %d\n", values[0], values[1], p[-1]);
    return 0;
}

Result

10 25 10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources