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?

3

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.