DEV Community

Calin Baenen
Calin Baenen

Posted on

Why do integral types get weirdly initialized inside of std::array in C++, and how can I fix it?

This was tested in SoloLearn's C++ Playground, I'm making the assumption my compiler will do something similar to the one SL uses.

So, I'm playing around with std::array<T, s>, because I plan on using it in my game.

When I do std::array<bool, 5> def; and print out the items in each index, I get:

Default 0: 0
Default 1: 0
Default 2: 0
Default 3: 0
Default 4: 0
Enter fullscreen mode Exit fullscreen mode

When I do std::array<std::string, 5> def;:

Default 0: 
Default 1: 
Default 2: 
Default 3: 
Default 4: 
Enter fullscreen mode Exit fullscreen mode

however, when I use an integral type like int, I get numbers that are totally random in some of the spots. - Only a few are actually initialized with 0 (like I expect).
Here's a sample:

Default 0: 1875674416
Default 1: 32568
Default 2: 0
Default 3: 0
Default 4: 4199168
Enter fullscreen mode Exit fullscreen mode

So, is there a way I can get these integral types to initialize properly? Or do I have to manually initialize the array with 0 (somehow)?

Top comments (4)

Collapse
 
deciduously profile image
Ben Lovy

I'm actually not sure why your bool example works, maybe someone else can chime in. Your declaration is not an initialization. The std::array will perform default initialization, which crucially is not the same as value-initialization. For primitive types, each element is undefined, meaning it has garbage. It's different for std::string because that's a class.

To fix it, you can ask for value-initialization instead using std::array<int, 5>{};.

Collapse
 
pgradot profile image
Pierre Gradot

We can't answer without a minimal code that reproduces that the issue.

Collapse
 
calinzbaenen profile image
Calin Baenen

Literally just do std::array<NumericDatatype, 5> arr; /* Code to print. */ and you'll get similar results.

Collapse
 
pgradot profile image
Pierre Gradot • Edited

arr is not initialized. So its actual content is not specified.

The behavior you observe is normal: there are random values in the array.

Sometimes, random values look like something you expect (like : all bools are false) but this is pure coincidence.