3

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?

IrAM
  • 1,720
  • 5
  • 18
hyun
  • 55
  • 8
  • Both create the `typedef` of the struct to `Node`, but in the first case, the struct itself has no tag, while in the second it has the tag `Node` as well. Stuct tag space and typedefs do not conflict. In the second case you can use either `Node` or `struct Node` to refer to the struct, in the first you are limited to referring to the type as `Node` only. To declare a pointer, you must have a type first. The second case is equivalent to `struct Node { struct Node *next; int data; }; typedef struct Node Node;` By using the tag you create a forward reference to `struct Node` – David C. Rankin Feb 02 '21 at 04:26
  • 1
    by "some compilers" you probably mean "some compilers for a different language" – M.M Feb 02 '21 at 04:26
  • 1
    In the first case `typedef struct` does not provide any information for `struct Node *next;` – David C. Rankin Feb 02 '21 at 04:30
  • _I don't know why in some compilers the prior code works_ can you please let us know what are those compilers, so that we can try. – IrAM Feb 02 '21 at 05:34
  • I am listening to a lecture that was uploaded years ago and the teacher uses Microsoft Visual Studio Community 2017 15.7.4 ver. In his lecture, the compiler for C language works fine with that code – hyun Feb 02 '21 at 05:57

1 Answers1

1

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.

bb94
  • 1,294
  • 1
  • 11
  • 24