Search code examples
cstructinitialization-list

How to initialize a structure on definition?


Is there a way to declare a structure with default initalisation values?

I have a header file which defines a structur like this:

typedef struct struc_s
{
    size_t cost const = 2000;
    size_t dmg const = 100;
    size_t def const = 100;
    size_t hull const = 1500;
    size_t shield const = 300;
    size_t capacity const = 2;
    size_t destruc const = 10;
} struc_t;

But this ofcourse doesn't work.

I would also be fine with a way of declaring a var of type struc_t in this header file. But as I remember right. I would have to decalre it in the c file as extern

What I want to do is every where where this header is included i want to be able to do var = struc_s.dmg and and the result should be that var holds the value 100. But I dont want to declare struc_s anywhere else then in the header. Is there a way to archive this behavior?


Solution

  • Not in the way you want.

    When you do a typedef, you're defining the shape of a memory region, a process distinct from allocating and filling it.

    A possible alternative:

    typedef struct 
    {
        size_t cost;
        size_t dmg;
        size_t def;
        size_t hull;
        size_t shield;
        size_t capacity;
        size_t destruc;
    } struc_t;
    
    
    #ifndef DEFAULT_STRUC_VALUES_DEFINED
    #define DEFAULT_STRUC_VALUES_DEFINED 
    
    const struc_t DEFAULT_STRUC = {
        .cost = 2000,
        .dmg = 100,
        .def = 100,
        .hull = 1500,
        .shield = 300,
        .capacity = 2,
        .destruc = 10
    };
    #endif
    

    and then when you want to create a new one:

    struc_t *new_struc = malloc(sizeof(struc_t));
    memcpy(new_struc, DEFAULT_STRUC, sizeof(struc_t));
    

    As a sidenote, is there a reason you're using size_t for your structure members? There's nothing inherently wrong with it, but it may change from platform to platform.