Iniesta8
Iniesta8

Reputation: 409

Init char array sensibly in C++?

I have a class respectively a struct with a member variable of type std::array<char, 100> called charArray. I want to initialize this array sensibly. Which values are sensible to init the array with and what is the best way to do this?

I think I could use std::fill() in constructor but is this the way I should really do it? I mean because of initialization vs. assignment?

Thanks.

Upvotes: 1

Views: 108

Answers (1)

NathanOliver
NathanOliver

Reputation: 180414

A simple solution would be to value initialize the array to the type's default value. Take for example

struct Foo
{
    std::array<int, 10> bar;
    Foo() : bar({}) {}
};

Here bar is would be initialized to all 0's. You can compare that with

struct Bar
{
    std::array<int, 10> baz;
};

Which would default initialize baz and its elements would have an indeterminate value. You can see all of this working with

struct Foo
{
    std::array<int, 10> bar;
    Foo() : bar({}) {}
};

struct Bar
{
    std::array<int, 10> baz;
};


int main(){
    Foo foo;
    for (auto e : foo.bar)
        std::cout << e << " ";
    std::cout << std::endl;
    Bar bar;
    for (auto e : bar.baz)
        std::cout << e << " ";
}

Possible output:

0 0 0 0 0 0 0 0 0 0 
-917263728 4197632 4197632 4197632 4197632 4197632 6295552 0 4197581 0 

Live Example

Upvotes: 1

Related Questions