Tal Dimant
Tal Dimant

Reputation: 1

Regarding forward declaration in c

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

typedef struct treeNode{

    imgPos position;
    treeNodeListCell *next_possible_positions;

}treeNode;


typedef struct segment{
    treeNode *root;
}Segment;

I'm quite confused about forward declaration on the struct above,what is the way to use current declaration?

Upvotes: 0

Views: 86

Answers (2)

user2371524
user2371524

Reputation:

So, from your example code, I understand you want to use typedefs for your structs and you need forward declarations. The most straight forward (sic) way would be like this:

typedef struct treeNode treeNode;
typedef struct treeNodeListCell treeNodeListCell;
typedef struct segment segment;

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

struct treeNode {
    imgPos position;
    treeNodeListCell *next_possible_positions;
};

struct segment {
    treeNode *root;
};

Be careful when you use an older standard than . In that case, repeating the typedef is not allowed, so any forward-declaration in a different header must look like this

struct treeNode;

and then use struct treeNode instead of treeNode to refer to the type.

With , this restriction is finally gone and you can repeat a typedef if the defined type is the same.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

You should write

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

In this case the type name struct treeNode is forward declared.

If the declaration looks like

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

then the compiler can not know what treeNode means.

Upvotes: 0

Related Questions