Search code examples
cinitializationdesignated-initializer

Is it possible to get pointer to the 'this' structure, when using designated initializer?


This kind of struct is used as head of linked list:

struct lista
{
    struct lista* next;
    struct lista* prev;
};

When next and prev both points to struct itself, then the list is empty. The following macro can be used for initializing the structure:

#define LISTA_INIT_EMPTY(list) { .next = (list), .prev = (list) }

this way:

struct lista my_list = LISTA_INIT_EMPTY(&my_list);

But, is there any way to do same thing by the following way, without macro parameter?:

struct lista my_list = LISTA_INIT_EMPTY;

I tried the following, but it caused a compile error:

#define LISTA_INIT_EMPTY     { .next = &.next, .prev = &.next }

Solution

  • Well, the only way I see is unpleasant:

    #define LISTA_INIT_EMPTY     { .next = (&my_list), .prev = (&my_list) }
    

    Not nice at all as it only works if your variable is called my_list. And there's no nice way as this does not exist in C.

    Why not using NULL instead of pointing to "this"? If this is not satisfactory, keeping the parameterized macro is probably the best.

    EDIT: (thanks to R's comment below, I finally understood the need):

    As there no "this" and to only enter the name of the variable once, I suggest using such a macro:

    #define CREATE_EMPTY_LISTA(name) struct lista name = { .next=&name, .prev=&name }
    

    And later in the code:

    CREATE_EMPTY_LISTA(my_list); // creates and initializez my_list at the same time