Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union initialization in C++ and C

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++.

like image 733
Alexander Oh Avatar asked Jul 19 '12 07:07

Alexander Oh


People also ask

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 do you initialize a union?

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 .

What is initialization in C?

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.

How many union members can be initialised?

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.


2 Answers

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

like image 87
hae Avatar answered Sep 23 '22 05:09

hae


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.)

like image 33
Kerrek SB Avatar answered Sep 21 '22 05:09

Kerrek SB