Search code examples
cstructvariable-declarationtype-declaration

C: struct with one less field. How do I declare/use it efficiently?


Assume we have two different struct that have mostly common fields but one or two different fields or less fields. For example:

typedef struct HobbyNodetag {
    char *name; // hobby name
    struct HobbyNodetag* link; // link to next HobbyNode
    int count; // number of times this hobby was mentioned by user
    // more fields... 
    // but identical type/variable name with MyHobbyList
} HobbyNode; // database of entire hobby node; singly linked list

typedef struct MyHobbyTag{
    char *name; // hobby name
    struct MyHobbyTag* link; // linked to next MyHobbyNode
    // more fields... 
    // but identical type/variable name with EntireHobbyList
} MyHobbyNode; // single person's hobby node; singly linked list

Do we have more efficient/elegant coding practice to use above two structs? Wouldn't this be a waste of having two different structs as they share majority of the fields?

UPDATE

My earlier question was misleading. The above example is the node and singly linked (by link).


Solution

  • You can move all the extra fields (which are present in the second struct but not in the first one) to the end of the struct type definition, then use the smaller struct as the "base" of the bigger one:

    struct BaseFoo {
        int count;
        char name[128];
        float value;
    };
    
    struct ExtendedFoo {
        struct BaseFoo base;
        struct ExtendedFoo *next;
    };
    

    What is nice about this solution is that you can have "polymorphism": since the C standard guarantees that there is no padding before the first struct member in memory, this will work just fine:

    void print_name(struct BaseFoo *foo)
    {
        printf("Count: %d\n", foo->count);
        printf("Name: %s\n", foo->name);
    }
    
    struct ExtendedFoo foo = { /* initialize it */ };
    print_name((BaseFoo *)&foo);