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++.
Using designated initializers, a C99 feature which allows you to name members to be initialized, structure members can be initialized in any order, and any (single) member of a union can be initialized. Designated initializers are described in detail in Designated initializers for aggregate types (C only).
Initializing Union Variable union data { int var1; double var2; char var3; }; union data j = {10}; This statement initializes the union variable j or in other words, it initializes only the first member of the union variable j .
Initialization is the process of locating and using the defined values for variable data that is used by a computer program. For example, an operating system or application program is installed with default or user-specified values that determine certain aspects of how the system or program is to function.
A union can be initialized on its declaration. Because only one member can be used at a time, only one can be initialized. To avoid confusion, only the first member of the union can be initialized.
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
I believe that C++11 allows you to write your own constructor like so:
union Foo { X x; uint8_t raw[sizeof(X)]; Foo() : raw{} { } };
This default-initializes a union of type Foo
with active member raw
, which has all elements zero-initialized. (Before C++11, there was no way to initialize arrays which are not complete objects.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With