For example, say we have a union
typedef union { unsigned long U32; float f; }U_U32_F;
When a variable of this union type is declared, is there a way to set an initial value?
U_U32_F u = 0xffffffff; // Does not work...is there a correct syntax for this?
You do not have to initialize all members of a union. The default initializer for a union with static storage is the default for the first component. A union with automatic storage has no default initialization.
Similarly, we can initialize the value of the third member at the time of declaration. union data k = { . var3 = 'a' }; The following program demonstrates the difference between a structure and a pointer.
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).
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.
Use an initializer list:
U_U32_F u = { 0xffffffff };
You can set other members than the first one via
U_U32_F u = { .f = 42.0 };
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