Designated Initialization in C99

2023-01-07

C99 introduces a new initialization method: designated initialization. This method is one of the few incompatibilities between C and C++, and it's rarely taught in schools. However, this syntactic sugar is very useful and can save a lot of typing.

Struct

struct S {
    int x;
    int y;
};

void foo() {
    struct S obj1 = {.x = 1, .y = 2};
    // obj1 = {1, 2}

    struct S obj2 = {.y = 2};
    // obj2 = {0, 2}
}

Array

void bar() {
    int a[5] = {[2] = 2, [4] = 4};
    // a = {0, 0, 2, 0, 4}
}

Mixing

struct S {
    int x;
    int y;
};

void uwu() {
    struct S sa[3] = {[1].y = 2};
    // sa = {{0, 0}, {0, 2}, {0, 0}}
}

Used for Heap Initialization

struct S {
    int x;
    int y;
};

void foo() {
    struct S *ptr = malloc(sizeof(struct S));
    *ptr = (struct S){.y = 2};
    // ptr->x == 0 && ptr->y == 2
}

See Also



Email: i (at) mistivia (dot) com