Union initialization in C++ and C

Alexander Oh picture Alexander Oh · Jul 19, 2012 · Viewed 38.5k times · Source

I have built a working C library, that uses constants, in header files defined as

typedef struct Y {
  union {
    struct bit_field bits;
    uint8_t raw[4];
  } X;
} CardInfo;

static const CardInfo Y_CONSTANT = { .raw = {0, 0, 0, 0 } };

I know that the .raw initializer is C only syntax.

How do I define constants with unions in them in a way such that I can use them in C and C++.

Answer

hae picture hae · Nov 22, 2013

I had the same problem. For C89 the following is true:

With C89-style initializers, structure members must be initialized in the order declared, and only the first member of a union can be initialized

I found this explanation at: Initialization of structures and unions