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