About default C struct values, what about this code?

后端 未结 8 1445
时光说笑
时光说笑 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:10

    ... create structs with default values ...

    That is impossible in C. A type cannot have default values. Objects of any type cannot have a default value other than 0, though they can be initialized to whatever is wanted.
    The definition of a struct is a definition of a type, not of an object.


    What you asking is about the same thing as a way to have ints default to, say, 42.

    /* WRONG CODE -- THIS DOES NOT WORK */
    typedef int int42 = 42;
    int42 a;
    printf("%d\n", a); /* print 42 */
    

    Or, adapting to your example

    /* WRONG CODE -- THIS DOES NOT WORK */
    struct stuff {
        int42 stuff_a;
        int65536 stuff_b;
    }
    struct stuff a;
    printf("%d\n", a.stuff_b); /* print 65536 */
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题