6
std::array<int,4> myInts;
std::array<bool,2> myBools;

Can the elements of myInts and myBools be assumed to be false and 0, or should I fill the arrays manually?

Andreas
  • 7,470
  • 10
  • 51
  • 73

1 Answers1

12

The elements will be set to random values, but you can make sure to value initialize them like this:

std::array<int,4> myInts{}; // all zeroes
std::array<bool,2> myBools{}; // all false

So the elements do not have to be reset, they can be initialized to certain values. You can also initialize elements to different values:

std::array<int,4> myInts{1,2,33,44};
std::array<bool,2> myBools{true, false};

If you have less elements than the size of the array in the initializer list, then the missing ones get zero initialized:

std::array<int,4> myInts{1,2}; // array contains 1,2,0,0

Note The standard specifies that std::array is an aggregate, and has some example code where it shows it implemented as having an array data member. It claims this is just to emphasize that the type is an aggregate, but if this implementation is used (and GCC uses it) then you would need an extra set of braces because you are initializing the array inside the std::array:

std::array<int,4> myInts{ {1,2,33,44} };

On the other hand, this case qualifies for brace elision, so the extra set of braces is not mandatory.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Would be a good addition to an answer, unfortunately you don't actually answer the question. –  Aug 14 '12 at 20:09
  • Thanks! Didn't know about the empty-list initialization. – Andreas Aug 14 '12 at 20:10
  • @delnan very true. I have made it into an answer now. – juanchopanza Aug 14 '12 at 20:11
  • `std::array` initialization requires a double set of braces ([unless you're using `=`](http://stackoverflow.com/questions/8863319/stdarrayt-initialization)) – Praetorian Aug 14 '12 at 20:13
  • @Prætorian well, I am still not 100% convinced about that one, and the standard seems a bit vague on the issue. I added a note about that. – juanchopanza Aug 14 '12 at 20:14
  • @juanchopanza: The Standard is not vague on the issue. It is pretty much clear (see [my detail answer here](http://stackoverflow.com/questions/11734861/when-can-outer-braces-be-omitted-in-an-initializer-list)). (well that doesn't mean that double set of braces is needed in your answer . +1 :-) ). – Nawaz Aug 14 '12 at 20:20
  • @Nawaz I read the relevant section and it didn't seem clear to me. I will read it again tomorrow with a fresh pair of eyes. – juanchopanza Aug 14 '12 at 20:21
  • @juanchopanza: You can read the section **"More on braces and extra braces"** in my answer. That is the most relevant part. – Nawaz Aug 14 '12 at 20:24
  • @Nawaz I even left a comment on that answer :-) My point is that it isn't clear to me that `std::array` **has** to be implemented as holding an array. – juanchopanza Aug 14 '12 at 20:26