What's the right way of using 'typedef'?

Viewed 92

I was writing the code in this way first

typedef struct 
{   
    struct Node *next;
    int data;
} Node;

because I learned that I can write struct without writing Node next to struct like this (if I use typedef)

typedef struct Node
{   
    struct Node *next;
    int data;
} Node;

But if I write without Node, later the warnings would appear when I'm using codes like Node *cur = head->next

The warning sign is:

'warning: incompatible pointer types initializing 'Node *' with an expression of type 'struct Node *''

(FYI I use mac os and visual studio code)

I know how to fix this but I don't know why in some compilers the prior code works and in some others it doesn't work.

And what is the best way to define struct? Is using typedef recommended?

1 Answers

Inside the structure definition, the name of the structure (struct Node) is visible, but the typedef (Node) isn't. Your first example doesn't give any name to the structure you're defining, only one to the typedef, and so the declaration of the next field in the structure definition is forward-declaring a new structure called struct Node, which is different from the anonymous structure you declared that's typedefed as Node.

Related