cstructsyntaxcyclic-dependency

Attempting to define two dependable structures in C


I am trying to define two structures in C when the second struct uses the first as an array member and has two pointer members of itself.

Visual Studio does not like my code:

syntax error : '}'
syntax error : identifier 'tokenListNode'
syntax error : missing '{' before '*'

any idea how to solve this?

--> Please note that the errors appear with or without the declarations I added at the beginning of the code.

--> In addition, if someone can explain to me what is the difference between the identifier before and after the struct's curly brackets, I'll be grateful.

Below is the code:

#define ARRAY_SIZE 100

struct tokenListNode;
struct TOKEN_LIST_NODE;


enum TOKEN_TYPE
{
id = 0,
INT_NUM,    
INT_REAL,         
ASSIGNMENT_OP,
RELATION_OP,
ARITHMETIC_OP
} tokenType;

typedef struct TOKEN
{
char* lexema;
enum TOKEN_TYPE type;
int lineNumber;
} token;


typedef struct TOKEN_LIST_NODE
{
token tokenArray[ARRAY_SIZE];
tokenListNode* prevNode;
tokenListNode* nextNode;
int tokenCounter;
}tokenListNode;

Solution

  • The definition of a structure is composed of the keyword struct; the "struct tag"; and the struct members

    struct tag { int member1; /* &c */ };
    

    You can leave the tag out and create an unnamed structure ... why you would do so is another matter: you can't refer to the structure without a struct tag!

    struct { int member1; /* &c */ };
    

    Also, you can take any type and give it another name using typedef

    typedef old_type new_name;
    

    as in

    typedef struct tag { int member1; /* &c */ } tag;
    /*      <------------ old type ------------> <new name> */
    

    The above line defines a struct (named struct tag) and, at the same time, gives that type a new name: tag

    what is the difference between the identifier before and after the struct's curly brackets

    That's the result of mixing definition of struct and typedef. The name before the {} is the "tag" of the structure, the name after the {} is the new name for the type being typedef'd.