Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do std::array elements have to be reset?

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?

like image 268
Andreas Avatar asked Aug 14 '12 20:08

Andreas


1 Answers

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.

like image 110
juanchopanza Avatar answered Nov 14 '22 03:11

juanchopanza