Search code examples
carrayscompound-literals

Reflecting inner struct in outer struct initialization


I have a code of structs stated as below:

typedef struct A {
  B numberOfB[3];
} A;

typedef struct B {
  int number1;
  int number2;
  boolean bool1;
  boolean bool2;
} B;

In the source code I have an initialization which looks like this:

A* pointerToA = (A[3]) {

  {5, 1, TRUE, TRUE,
   6, 1, TRUE, FALSE,
   7, 1, TRUE, FALSE},

  {5, 1, TRUE, TRUE,
   6, 1, TRUE, FALSE,
   7, 1, TRUE, FALSE},

  {5, 1, TRUE, TRUE,
   6, 1, TRUE, FALSE,
   7, 1, TRUE, FALSE},
}

Such construction in source code is updating fields in struct B but I do not understand how are fields in B are updated as the values are just listed as it was a array of 12 values. Could someone explain that in details?


Solution

  • Reflecting the substructure in an initializer is optional. So here having 12 value is sufficient to initialize an A.

    This is really bad style though, I think, since it makes the code quite difficult to read. Much better would even be to use designated initializers such that the initialization becomes robust versus changes of the structure. Something like

    [0] = {.number1 = 5, .number2 = 1, .bool1 = true, .bool2 = true, },
    

    Also observe that C has a proper Boolean type and constants that you best use through the header <stdbool.h> as bool, false and true.