About default C struct values, what about this code?

后端 未结 8 1479
时光说笑
时光说笑 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 16:12

    Can't initialize values within a structure definition.

    I'd suggest:

    typedef struct {
       int stuff_a;
       int stuff_b;
    } stuff ;
    
    int stuffInit(int a, int b, stuff *this){
       this->stuff_a = a;
       this->stuff_b = b;
       return 0; /*or an error code, or sometimes '*this', per taste.*/
    }
    
    
    int main(void){
       stuff myStuff;
       stuffInit(1, 2, &myStuff);
    
       /* dynamic is more commonly seen */
       stuff *dynamicStuff;
       dynamicStuff = malloc(sizeof(stuff));  /* 'new' stuff */
       stuffInit(0, 0, dynamicStuff);
       free(dynamicStuff);                    /* 'delete' stuff */
    
       return 0;
    }
    

    Before the days of Object Oriented Programming (C++), we were taught "Abstract Data Types".

    The discipline said 'never access your data structures directly, always create a function for it' But this was only enforced by the programmer, instructor, or senior developer, not the language.

    Eventually, the structure definition(s) and corresponding functions end up in their own file & header, linked in later, further encapsulating the design.

    But those days are gone and replaced with 'Class' and 'Constructor' OOP terminology.

    "It's all the same, only the names have changed" - Bon Jovi.

提交回复
热议问题