Home > OS >  Nested designated initializers
Nested designated initializers

Time:11-21

Does C 20 allows nested designated initializers? E.g:

struct Outer {
  int32_t counter;
  struct {
    std::string name;
  } inner;

  struct {
    std::optional<int32_t> value;
  } inner_optional;
};

Outer outer = {
    .counter = 100,
    .inner = {
        .name = "test" // nested
    }
};

If this is allowed, can someone provide a link to a trusted source? I can't find it on cppreference.

CodePudding user response:

Yes, this is supported, cppreference - aggregate initialization states:

If the initializer clause is a nested braced-init-list (which is not an expression), the corresponding array element/class member/public base (since C 17) is list-initialized from that clause: aggregate initialization is recursive.

List initialization is aggregate initialization for aggregates.

Note that truly nested C designated initializers, i.e doing outer = {.inner.name = ""};, are not supported in C . The required workaround is exactly what you have wrote.

CodePudding user response:

Yes, the shown program is well-formed.

Same rules apply to the inner initialisers as apply to the outermost initialiser. The outermost initialiser is not special in regard to designated initialisers.

  • Related