r/C_Programming • • Jul 06 '26

Question anonymously initializing static pointers in self-referential data-structures?

I have a recursive data-structure (a simple linked list for purposes of this example) and wanted to statically define a linked-list. The following works fine:

#include <stdio.h>
typedef struct mytype_tag {
    struct mytype_tag* next;
    char* data;
} mytype;

mytype a = {
    .next = NULL,
    .data = "a",
};
mytype b = {
    .next = &a,
    .data = "b",
};

int
main() {
    mytype* s = &b;
    int i = 0;
    while (s) {
        printf("%d: %s\n", i++, s->data);
        s = s->next;
    };
}

However, I have to explicitly define/declare a and then have b take &a.

Is there a way to do this with anonymous/unnamed intermediary structures, thinking an imaginary syntax something like

mytype b = {
    .next = &((mytype)={
        .next = NULL,
        .data = "a",
        }),
    .data = "b",
};

so I can build up the linked-list without naming each intermediary instance?

16 Upvotes

30 comments sorted by

View all comments

Show parent comment

3

u/atariPunk Jul 06 '26

That code is only valid in c99 and above.
It works because clang and gcc accept it as an extension.
If you compile it with the pedantic flag you will get warnings.

1

u/gumnos Jul 06 '26

ooh, nice to know. Thanks!

1

u/gumnos Jul 06 '26

I should have noticed that it was using the .data = … initializer notation which isn't C89 yet the compiler didn't grouse about it.

1

u/ReallyEvilRob Jul 06 '26

It's kind of funny how divergent C and C++ are becoming with each new standard in spite of Bjarne Stroustrup originally intending on C++ being a superset of C.