Search code examples
cstructforward-declaration

Forward declare a struct in C


How do I forward declare the following treeNodeListCell struct?

I tried writing struct treeNodeListCell before the struct definitions and the code doesn't compile.

Does anyone have an idea?

struct treeNodeListCell;

typedef struct _treeNode {
    treeNodeListCell *next_possible_positions;
} treeNode;

typedef struct _treeNodeListCell {
    treeNode *node;
    struct _treeNodeListCell *next;
} treeNodeListCell;

Solution

  • You can forward declare a struct, but when you do, you need to use the struct keyword with the forward-declared struct tag.

    struct _treeNodeListCell;
    
    typedef struct _treeNode {
        struct _treeNodeListCell *next_possible_positions;
    } treeNode;
    
    typedef struct _treeNodeListCell {
        treeNode *node;
        struct _treeNodeListCell *next;
    } treeNodeListCell;
    

    The alternative is a forward-declared typedef. C allows you to typedef an incomplete type, which is to say that you can typedef the structure before defining the structure. That allows you to use the typedef in the structure definition.

    typedef struct _treeNodeListCell treeNodeListCell;
    
    typedef struct _treeNode {
        treeNodeListCell *next_possible_positions;
    } treeNode;
    
    struct _treeNodeListCell {
        treeNode *node;
        treeNodeListCell *next;
    };
    

    If you want to use the structures in the question without changing them, all you need is the typedef before the structure definitions.

    typedef struct _treeNodeListCell treeNodeListCell;
    
    typedef struct _treeNode {
        treeNodeListCell *next_possible_positions;
    } treeNode;
    
    typedef struct _treeNodeListCell {
        treeNode *node;
        struct _treeNodeListCell *next;
    } treeNodeListCell;