About default C struct values, what about this code?

后端 未结 8 1484
时光说笑
时光说笑 2020-12-31 15:27

I\'m trying to create structs with default values. I don\'t know how to accomplish this because every code that I see, is about initialising, and I would it for the natural

8条回答
  •  庸人自扰
    2020-12-31 15:50

    I'm not sure quite sure what your problem is. The standard way of initialising structures in c is like this:

    struct a_struct my_struct = {1, 2};
    

    Or the more recent and safer:

    struct a_struct my_struct = {.i1 = 1, .i2 = 2};
    

    If there is more than one instance of a structure, or it needs to be re-initialised, it is useful to define a constant structure with default values then assign that.

    typedef struct a_struct {
       int i1;
       int i2;
    } sa;
    
    static const sa default_sa = {.i1 = 1, .i2 = 2};
    
    static sa sa1 = default_sa;
    static sa sa2 = default_sa;
    
    // obviously you can do it dynamically as well
    void use_temp_sa(void)
    {
         sa temp_sa = default_sa;
         temp_sa.i2 = 3;
         do_something_with(&temp_sa);
    }
    
    // And re-initialise
    void reset_sa(sa *my_sa)
    {
        *my_sa = default_sa;
    }
    

提交回复
热议问题