Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

❯ 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading