Are members of a C++ struct initialized to 0 by default?

C++

C++ Problem Overview


I have this struct:

struct Snapshot
{
    double x; 
    int y;
};

I want x and y to be 0. Will they be 0 by default or do I have to do:

Snapshot s = {0,0};

What are the other ways to zero out the structure?

C++ Solutions


Solution 1 - C++

They are not null if you don't initialize the struct.

Snapshot s; // receives no initialization
Snapshot s = {}; // value initializes all members

The second will make all members zero, the first leaves them at unspecified values. Note that it is recursive:

struct Parent { Snapshot s; };
Parent p; // receives no initialization
Parent p = {}; // value initializes all members

The second will make p.s.{x,y} zero. You cannot use these aggregate initializer lists if you've got constructors in your struct. If that is the case, you will have to add proper initalization to those constructors

struct Snapshot {
    int x;
    double y;
    Snapshot():x(0),y(0) { }
    // other ctors / functions...
};

Will initialize both x and y to 0. Note that you can use x(), y() to initialize them disregarding of their type: That's then value initialization, and usually yields a proper initial value (0 for int, 0.0 for double, calling the default constructor for user defined types that have user declared constructors, ...). This is important especially if your struct is a template.

Solution 2 - C++

No, they are not 0 by default. The simplest way to ensure that all values or defaulted to 0 is to define a constructor

Snapshot() : x(0), y(0) {
}

This ensures that all uses of Snapshot will have initialized values.

Solution 3 - C++

In general, no. However, a struct declared as file-scope or static in a function /will/ be initialized to 0 (just like all other variables of those scopes):

int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0

void foo() {
  struct { int a, b; } bar; // undefined
  static struct { int c, d; } quux; // 0, 0
}

Solution 4 - C++

With POD you can also write

Snapshot s = {};

You shouldn't use memset in C++, memset has the drawback that if there is a non-POD in the struct it will destroy it.

or like this:

struct init
{
  template <typename T>
  operator T * ()
  {
    return new T();
  }
};

Snapshot* s = init();

Solution 5 - C++

In C++, use no-argument constructors. In C you can't have constructors, so use either memset or - the interesting solution - designated initializers:

struct Snapshot s = { .x = 0.0, .y = 0.0 };

Solution 6 - C++

Since this is a POD (essentially a C struct) there is little harm in initialising it the C way:

Snapshot s;
memset(&s, 0, sizeof (s));

or similarly

Snapshot *sp = new Snapshot;
memset(sp, 0, sizeof (*sp));

I wouldn't go so far as to use calloc() in a C++ program though.

Solution 7 - C++

I believe the correct answer is that their values are undefined. Often, they are initialized to 0 when running debug versions of the code. This is usually not the case when running release versions.

Solution 8 - C++

Move pod members to a base class to shorten your initializer list:

struct foo_pod
{
    int x;
    int y;
    int z;
};

struct foo : foo_pod
{
    std::string name;
    foo(std::string name)
        : foo_pod()
        , name(name)
    {
    }
};

int main()
{
    foo f("bar");
    printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}

Solution 9 - C++

I know this question is super old, but this question popped up for me on google and I found this other way and figured I'd add it here:

Snapshot s {};

I'm not sure what C/C++ language version you need for this syntax.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSashaView Question on Stackoverflow
Solution 1 - C++Johannes Schaub - litbView Answer on Stackoverflow
Solution 2 - C++JaredParView Answer on Stackoverflow
Solution 3 - C++bdonlanView Answer on Stackoverflow
Solution 4 - C++AndersKView Answer on Stackoverflow
Solution 5 - C++Adrian PanasiukView Answer on Stackoverflow
Solution 6 - C++finnwView Answer on Stackoverflow
Solution 7 - C++EricView Answer on Stackoverflow
Solution 8 - C++Bruno MartinezView Answer on Stackoverflow
Solution 9 - C++SimoydView Answer on Stackoverflow