Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Must use 'struct' tag to refer to type 'node'"

What is happening here? I'm getting

Must use 'struct' tag to refer to type 'node'

on the gx and hx lines of

typedef struct node {
    char * fx; // function
    node * gx; // left-hand side
    char * op; // operator
    node * hx; // right-hand side    
} node;

I've also tried

typedef struct node {
    char * fx; // function
    node * gx; // left-hand side
    char * op; // operator
    node * hx; // right-hand side
};

and

struct node {
    char * fx; // function
    node * gx; // left-hand side
    char * op; // operator
    node * hx; // right-hand side
};

and

typedef struct  {
    char * fx; // function
    node * gx; // left-hand side
    char * op; // operator
    node * hx; // right-hand side
} node;

and

typedef struct treeNode {
    char * fx; // function
    treeNode  * gx; // left-hand side
    char * op; // operator
    treeNode * hx; // right-hand side
} node;

and I get errors for all of those. What is the proper syntax in plain C again?

like image 739
Microsoft Orange Badge Avatar asked May 26 '15 01:05

Microsoft Orange Badge


3 Answers

Let's look at the first snippet:

typedef struct node {
    char * fx; // function
    node * gx; // left-hand side
    char * op; // operator
    node * hx; // right-hand side    
} node;

gx and hx occur in the middle of the struct node/node type definition, before the typedef statement is complete. At this point in the program, node is not a valid type name, because the typedef isn't over yet (and, unlike C++, writing struct node { ... }; does not automatically make node a type name). However, struct node is a valid type name at this point (as long as you only use it for pointer types), so in order to declare gx and hx properly, you need to write:

typedef struct node {
           char * fx; // function
    struct node * gx; // left-hand side
           char * op; // operator
    struct node * hx; // right-hand side    
} node;
like image 144
jwodder Avatar answered Oct 27 '22 21:10

jwodder


In c, you can't use the structure name to refer to the struct, you need to add struct before the name, or you could typedef it, like

typedef struct node node;

struct node 
 {
    /* Whatever */
    node *link;
 };
like image 31
Iharob Al Asimi Avatar answered Oct 27 '22 21:10

Iharob Al Asimi


I do it like this

struct node {
    char        * fx;   // function
    struct node * gx;   // left-hand side
    char        * op;   // operator
    struct node * hx;   // right-hand side
};
typedef struct node node;
like image 3
dave234 Avatar answered Oct 27 '22 22:10

dave234