Search code examples
cstructtypedef

How to properly use typedef for structs in C


I have a struct for a linked list in my C code. When the list is defined like this:

typedef struct LinkedList {
    Ht_item* item;
    LinkedList* next;
}LinkedList;

I get the Compilation Error: "error: unknown type name ‘LinkedList’" alongside other related error messages

However, when i define my LinkedList this way:

typedef struct LinkedList LinkedList;

struct LinkedList {
    Ht_item* item;
    LinkedList* next;
};

I get no errors.

I do not understand why the Error happens in the first instance?


Solution

  • In this definition:

    typedef struct LinkedList {
        Ht_item* item;
        LinkedList* next;
    }LinkedList;
    

    You're using the type LinkedList before it's been defined or declared.

    This works:

    typedef struct LinkedList LinkedList;
    
    struct LinkedList {
        Ht_item* item;
        LinkedList* next;
    };
    

    Because LinkedList has been declared (but not fully defined) by the time it's used, and because you're creating a pointer to that type it doesn't need to be fully defined yet.

    This would also work:

    typedef struct LinkedList {
        Ht_item* item;
        struct LinkedList* next;
    }LinkedList;
    

    For the same reason the prior piece of code works.