Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

Designated initializer

A designated initializer selects a structure or union member, or an array element, instead of selecting it solely by its position in the list.

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

Syntax

struct Type object = { .member = value };
Element array[N] = { [index] = value };

A designated initializer appears in an initializer list inside {}. .member = value selects a structure or union member, while [index] = value selects an array element. This is initialization, not a later assignment.

Structure members can be designated out of declaration order. An index must be an integer constant expression with a nonnegative value. For an array of known size, the index must be within the array bounds. For an array of unknown size, there is no preexisting upper bound, and the designated index can help determine the array size. A following initializer without a designator continues with the next subobject: after [2] = 8, the value 9 initializes the element at index 3.

Omitted int elements receive 0, even in a local array. In the example, .y precedes .x, but the result is 3 7; the array contains 0 0 8 9 0.

Examples

#include <stdio.h>

struct Point { int x; int y; };

int main(void)
{
    struct Point p = { .y = 7, .x = 3 };
    int a[5] = { [2] = 8, 9 };

    printf("%d %d\n", p.x, p.y);
    printf("%d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4]);
    return 0;
}

Result

3 7
0 0 8 9 0

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