Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typedef struct <struct_name> vs simply typedef struct

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

What is the difference between these two, i.e between struct Node <name> and Node <name>?
Using the second one gives an error.

I am a bit new to C and I have seen the first one used when it is necessary to define the same struct inside the struct definition. Does it actually define the same struct or is it a different struct being defined?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In C, an identifier need to be declared before use. An identifier may be a variable name, a struct tag name, a typedef, a function name, etc. Without a declaration the compiler cannot possibly know what an identifier refers to.

In your first snippet, struct Node alone declares Node as a struct. Since the type is already declared (but its defintion is still incomplete, this is called an "incomplete type"), it can be used in limited ways, including declaring a member of a pointer to the type. The definition of the struct is complete at the point of the closing bracket.

In the second snippet, an unnamed struct is declared and at the point you use Node, there is no previous declaration and hence the compiler cannot figure out what the identifier Node refers to, hence it cannot be used in the way as shown in your snippet.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading