Edmund's blog

Writing code.

Initializing a struct

This is how a lot of people initialize their plain old data structs.

1
2
3
4
5
6
7
8
9
struct MyStruct
{
    double first;
    int second;
    char third[4];
};

MyStruct my;
memset(&my, 0, sizeof(my));

That memset is a lot of typing. Isn’t there a simpler way?

1
2
3
4
5
6
7
MyStruct my1;               // uninitialized
MyStruct my2 = { 2.0 };     // partially zero-initialized
MyStruct my3 = {};          // completely zero-initialized
MyStruct my4 = MyStruct();  // zero-initialized

MyStruct my5();  // function declaration (oops!)
MyStruct my6{};  // uniform initialization (C++11)

Note the partial initialization of my2. The remaining fields are zero-initialized.

My favorite way is my3. It almost looks like my6, but it doesn’t require C++11.

What about creating structs on the heap?

1
2
MyStruct* pMy1 = new MyStruct;    // uninitialized
MyStruct* pMy2 = new MyStruct();  // zero-initialized

Those parentheses make a huge difference!

Static data is always initialized.

1
static MyStruct s_my;  // zero-initialized

How about arrays?

1
2
3
4
5
6
7
MyStruct arr1[5];       // uninitialized
MyStruct arr2[5] = {};  // zero-initialized

MyStruct* arr3 = new MyStruct[5];    // uninitialized
MyStruct* arr4 = new MyStruct[5]();  // zero-initialized

std::vector<MyStruct> vec(5);  // zero-initialized

Like all STL containers, std::vector always initializes its data.