Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zero-initialize an union?

Tags:

c++

Consider the following code:

struct T {
    int a;
    union {
        struct {
            int a;
        } s1;
        struct {
            char b[1024];
        } s2;
    };
};

int main() {
    T x = T();
}

Since an explicit constructor is called, the above code ends-up zero-initializing all the data members in x.

But I would like to have x zero-initialized even if an explicit is not called. To do that one idea would be to initialize the data members in their declaration, which seems to be okay for T::a. But how can I zero-initialize all the memory occupied by the union by using the same criteria?

struct T {
    int a = 0;
    union {
        struct {
            int a;
        } s1;
        struct {
            char b[1024];
        } s2;
    };
};

int main() {
    T x; // I want x to be zero-initialized
}
like image 662
Martin Avatar asked Aug 04 '12 22:08

Martin


1 Answers

You could zeroize using memset:

memset(&x, 0, sizeof(x));
like image 106
MRAB Avatar answered Oct 04 '22 19:10

MRAB