1

I have the following data structures

struct single_t
{
    uint16_t i1 = 0;
    uint8_t i2 = 0;
    uint8_t i3 = 0;
};

struct mapping_t
{
    uint8_t n1;
    uint8_t n2;
    bool enable;
    uint n3;
    std::array<single_t, 32> map;
};

I want to initialize them in the following way:

mapping_t m1 {
    3,                                  // n1
    254,                                // n2
    true,                               // enable
    5,                                  // n3

    // map
    // i1                   i2              i3
    {{
        {0x1000,            1,              8}
    }}
};

can i be sure, that the elements in the std::array<single_t, 32> map;, in this case indexes 1..31, are initialized to 0 or is it like the uninitialized variable on the stack int i; ? My debugger shows they are at 0, but is that implementation dependent on the debug build or is this defined in the standard?

1
  • The elements 1 - 31 of m1 are value initialized, i.e. initialized to zero in your case. Your code is fine. Commented Feb 25, 2017 at 8:20

1 Answer 1

2

From http://en.cppreference.com/w/cpp/language/aggregate_initialization

If the number of initializer clauses is less than the number of members or initializer list is completely empty, the remaining members are value-initialized. If a member of a reference type is one of these remaining members, the program is ill-formed.

The default case for value initialization is to initialize with 0

See http://en.cppreference.com/w/cpp/language/value_initialization

The effects of value initialization are:

[...]

4) otherwise, the object is zero-initialized.

To sumarize, you're fine !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.