Home > Back-end >  C struct compound initialization without setting everything to zero
C struct compound initialization without setting everything to zero

Time:08-02

Is there any syntax similar to doing something like this

typedef struct foo
{
   int X;
   int Y;
   int Z;
} foo;

int main()
{
   // Initialize everything
   foo Variable = (foo){
    .X = 10;
    .Y = 15;
    .Z = 20;
   };

  // Assign the X and Y variables, but keep Z the same
  Variable = (foo){
   .X = 15;
   .Y = 20;
  // .Z stays the same
  };
}

Would be nice to have this type of QOL syntax instead of having to type

int main()
{
   foo Variable = {bla bla};

   // Keep having to type Variable. to access struct members
   Variable.X = 10;
   Variable.Y = 15;
}

This gets really annoying with structs in structs i.e.

Struct1->Struct2.Struct3.Element.X = 10;
Struct1->Struct2.Struct3.Element.Y = 15;

CodePudding user response:

No, C does not support this style of initialization or assignment.

If you want to access only a part of a structure, you need to express this explicitely.

EDIT:

You can get away with:

    Variable = (foo){
       .X = 15;
       .Y = 20;
       .Z = Variable.Z;
    };

At least an optimizing compiler will just generate the operations for the changing elements. But it is more source than single assignments.

CodePudding user response:

You can use the preprocessor to save your fingers (or copy/paste)...

    struct {
        int f1;
        int f2;
        struct {
            int b1;
            int b2;
            int b3;
        } bar;
    } foo = {
        1, 2, { 42, 43, 44 },
    };

    printf( "%d  %d  %d\n", foo.bar.b1, foo.bar.b2, foo.bar.b3 );
#define S foo.bar
    S.b1 = 7;
    S.b2 = 8;
    printf( "%d  %d  %d\n", S.b1, S.b2, S.b3 );
#undef S
  • Related