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

How to initialize char[] in a struct with constexpr char[] using initializer list?

I have a struct like:

constexpr char defaultName[6] = "Hello";

struct MyStruct{
   char name[6];
   int val;
};

Now I want to initialize the struct using initializer list as following:

MyStruct structObj{defaultName, 0};

However, this doesn’t work. How do I initialize the char array in initializer using defaultName?

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

I used MyStruct structObj{defaultName, 0}; but this doesn’t work. I know I can do {"Hello", 0} but I would like to use constexpr. Also, strcpy works but just wanted to know if there is a way to use the defaultName in initializer list.

Note: The struct is defined in a common library C header which is used by the C++ code so I can’t update the struct definition.

>Solution :

Arrays aren’t copiable normally, but std::array is

constexpr std::array<char,6> defaultName {'H', 'e', 'l', 'l', 'o', '\0'};

struct MyStruct{
   std::array<char,6> name;
   int val;
};

MyStruct structObj{defaultName, 0};

If you can’t update the struct, then use a default struct instead:

struct MyStruct{
   char name[6];
   int val;
};
constexpr MyStruct defaultStruct{"Hello",0};

MyStruct structObj(defaultStruct);
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