c++c++11uniondesignated-initializer

C++11 designated initializers for Union


Why do designated initializers for union work in C++11?

According to doc, it is C++20 feature https://en.cppreference.com/w/cpp/language/aggregate_initialization

union u { int a; const char* b; };
// C++20 designated initializer lists
u d = {.b = "asdf"};         // OK: can explicitly initialize a non-initial member

But I can compile this

❯ cat union.cc
union U{
  int a;
  float b;
};

int main(){
  auto u = U{.a=3};
  return 0;
}
~/code/des_init                                                                                                                                                 
❯ gcc ./union.cc -std=c++11

Solution

  • C added designated initializers to the language. Many C++ compilers implemented it in C, and in non-strict conformance mode allowed C++ programs to use the feature.

    It was added to C++ with a few restrictions later (such as a requirement to do the initializers in order).

    Tell your compiler to use strict conformance to block some or all extensions to the language they include by default.

    -pedantic and -Werror and/or -pedantic-errors are all ways to block various extensions.

    See How to disable GNU C extensions? for someone talking about this from the perspective of C; many of the same flags work in C++.

    gcc by default seeks to compile valid programs, but does not guarantee to reject all invalid programs.