Search code examples
cstructdeclarationtypedef

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?


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.