Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a union be initialized in the declaration?

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? 
like image 883
semaj Avatar asked Jan 27 '10 17:01

semaj


People also ask

Can I initialize unions?

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.

How can you initialize a union at the time of declaration?

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.

Can we initialize union in 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).

How many union members can be initialize?

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.


1 Answers

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 }; 
like image 92
Christoph Avatar answered Sep 29 '22 05:09

Christoph