Question

I have a structure, which I need to initialize at compile time. Here is the current (pseudo)code:

struct A
{
    int a;
    int b;
};

struct B
{
    struct A а[16][3];
};

#define DEFAULT {{ \
                   .a = 1, \
                   .b = 2, \
                 }, \ 
                 { \
                   .a = 3, \
                   .b = 8, \
                 }, \
                 { \
                   .a = 11, \
                   .b = 29, \
                }}

#define DEFAULT2 DEFAULT, DEFAULT
#define DEFAULT4 DEFAULT2, DEFAULT2
#define DEFAULT8 DEFAULT4, DEFAULT4
#define DEFAULT16 DEFAULT8, DEFAULT8

struct B b = {{DEFAULT16}};

I don't understand this code:

  • Why do we need double braces on the last line?
  • Moreover, why do we need the double braces in the definition of DEFAULT. I understand that

                 {
                   .a = 3,
                   .b = 8,
                 }
    

is an ordinary structure initialization. But the second pair of braces seems as if I am initializing b as an array of 16 objects of type struct A [3]. Why not simply list the values of b as if it were a 1-dimensional array (the same way that one can access b[20])?

  • Thirdly, now I need to add a new field to struct B and have no idea how to modify the initialization. The new struct B shall be:

                 struct B
                 {
                    int c[16];
                    struct A a[16][3];
                 }
    

Compiler is arm-none-eabi-gcc 4.7.2 with no flags to enforce any C standard.

Was it helpful?

Solution

If I understand correctly,

One brace is needed for things within struct A, e.g.

struct A a = { .a = 1, .b = 2 };

Two braces are needed for a two dimensional array, e.g.

int array[2][2] = {
  { 1, 1 },
  { 1, 1 }
};

The final brace is needed for things within struct B.

Finally, to add int c[16] to struct B, you can replace the last line of your snippet with the following:

struct B b = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},{DEFAULT16}};

Or use proper macro substitution for readability.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top