简体   繁体   中英

In struct nested union/array member default initialization compiles, but is not happening correctly?

I am trying to initialize array members at struct declaration in the following struct with nested union & array:

struct Nested
{

  union 
  {  
    short sArray[5] = {42};
    float fVal;  // Must NOT be initialized - obviously, only 1 member of a union can be
  };

  double dArray[5] = {77.7};

};

While the code compiles just fine, only first elements of both arrays are initialized, when running/debugging the code..

sArray[0] is set to 42, remaining elements are all set to 0 dArray[0] is set to 77.69999, remaining are all set to 0

All other answers I found, mention initialization at instance declaration, but not default init in struct/class declaration. I have not seen/found whether this syntax is enabled (for array members too) by gnu c++17. However, since it compiles WO warning one would assume it should correct. Am I doing something wrong?

Edit: Or how do I simply initialize my arrays?

What you are doing is aggregate initialization , which means the elements in sArray and dArray arevalue initialized when not specified. Because short and double are scalar types, this means zero initialization

Since you don't specify anything but the first element, all remaining elements will be initialized to 0

Since @eike does not seem to respond to my suggestion to show the final solution, let me paste a solution here, based on @eike's hint in his comment.

struct Nested
{
 // Initialize your arrays in c-tor(s)
 Nested()
 {
   std::fill_n(sArray, 5, 42);
   std::fill_n(dArray, 5, 77.7);
 }
...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM