About default C struct values, what about this code?

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

    If you want to set a struct object in one go and you have a C99 compiler, try this:

    struct stuff {
        int stuff_a;
        int stuff_b;
        // and so on...
    };
    
    struct stuff foo;
    /* ... code ... */
    foo = (struct stuff){.stuff_b = 42, .stuff_a = -1000};
    

    Otherwise, with a C89 compiler, you have to set each member one by one:

    foo.stuff_b = 42;
    foo.stuff_a = -1000;
    

    Running example @ ideone : http://ideone.com/1QqCB


    The original line

    struct a{   a() : i(0), j(0) {}   INT i;   INT j;}
    

    is a syntax error in C.

提交回复
热议问题