Can a union be initialized in the declaration?

semaj picture semaj · Jan 27, 2010 · Viewed 16.1k times · Source

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?

Answer

Christoph picture Christoph · Jan 27, 2010

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 };