Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to union

Having limited experience with unions in C++, I am struggling to understand the basic mechanics of casting to/from that datatype.

Suppose two types Type_a and Type_b are wrappers of type int and long respectively.

A union is defined as:

union Type_u {
    Type_a a;
    Type_b b;
}

Now I have something of type Type_a, lets call it j (Just to be confusing). I need to pass it to a function that expects a parameter of type Type_u:

void burninate(Type_u peasants);

What is the proper way to pass this variable j to burninate? (I've run into issues casting j to Type_u as well as passing it in as-is. Neither compiled.)

It may be worth pointing out that I have no ability to modify the union type (or Type_a or Type_b or burninate's signature for that matter.)

like image 645
BlackVegetable Avatar asked Nov 09 '13 02:11

BlackVegetable


1 Answers

Since Type_a is the first element, you can initialize a union like this:

Type_a j;
Type_u u = {j};
burninate(u);

If you want to pass a type of Type_b:

Type_b k;
Type_u u;
u.b = k;
burninate(u);

There is a difference on this in C and C++. In C99, you can use designated initializer to initialize elements that isn't the first.

Type_b k;
Type_u u = {.b = k};
burninate(u);
like image 197
Yu Hao Avatar answered Sep 19 '22 04:09

Yu Hao