0

I have a struct inside a struct and on initialization of the outer struct I want to initialize the inner struct as const.

typedef struct A {
  uint16_t id;
}A;

typedef struct B {
  A a;
  uint16_t data;
}

I know I can initialize the inner struct when initializing the outer struct by this code:

B test = {
  {
    .id = 0x100
  },
  .data = 0
};

I know I can do it this way:

const A aTest = {
  .id = 0x100
};
B test = {
  .a = aTest,
  .data = 0

But is there a way to make the inner initialization directly constant?

oliverleo
  • 77
  • 9
  • 2
    What do you mean by "make this inner initialization constant"? Can you please elaborate? – Some programmer dude Jun 27 '16 at 13:19
  • Possible duplicate of [How to initialize a struct in accordance with C programming language standards](http://stackoverflow.com/questions/330793/how-to-initialize-a-struct-in-accordance-with-c-programming-language-standards) – wigy Jun 27 '16 at 13:20
  • Do you mean that `B test = { .data = 0 };` should set `test.a.id` implicitly to `0x100`? – user694733 Jun 27 '16 at 13:22

1 Answers1

1

You need to define the inner member as const:

typedef struct B {
  const A a;
  uint16_t data;
} B;

Then you can initialize like this:

B test = {
  {
    .id = 0x100
  },
  .data = 0
};

While this generates a compiler error:

test.a.id=1;
dbush
  • 205,898
  • 23
  • 218
  • 273