Search code examples
cstructcircular-reference

Am I allowed to make circular references with constants structs?


Am I allowed to do this in C99?

typedef struct dlNode {
    dlNode* next, prev;
    void* datum;
} dlNode;

const static dlNode head={
    .next = &tail,
    .prev = NULL,
    .datum = NULL
};

const static dlNode tail={
    .next = NULL,
    .prev = &head,
    .datum = NULL
};

I can make my program work without this. It'd just be convenient.


Solution

  • You can. You just have to forward declare tail to get it to work:

    typedef struct dlNode {
        struct dlNode* next;
        struct dlNode* prev;
        void* datum;
    } dlNode;
    
    const static dlNode tail;
    
    const static dlNode head={
        .next = &tail,
        .prev = NULL,
        .datum = NULL
    };
    
    const static dlNode tail={
        .next = NULL,
        .prev = &head,
        .datum = NULL
    };