Reputation: 3
typedef struct node{
int val;
node *next;
} node;
node *start;
Here this code throws an error on line 3. But if I modify it like this,
typedef struct node{
int val;
struct node *next;
} node;
node *start;
This is correct? But why the compiler do so? And how the compiler execute it?
Upvotes: 0
Views: 43
Reputation: 24052
The problem is that the node
type doesn't exist until after the end of the typedef
declaration, so it cannot be referenced in the structure body. But the structure tag in struct node
can.
My preferred solution is to declare the typedef
using a forward reference to the structure definition, then define the structure in a second declaration. The advantage is that it allows the typedef
name to be used inside the structure defintion. It looks like this:
typedef struct node node;
struct node {
int val;
node *next;
};
This allows you to use the typedef
name node
consistently in all declarations, including the ones inside the structure definition.
Upvotes: 1