Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check what type is currently used in union?

Tags:

c

unions

let's say we have a union:

typedef union someunion {     int a;     double b; } myunion; 

Is it possible to check what type is in union after I set e.g. a=123? My approach is to add this union to some structure and set uniontype to 1 when it's int and 2 when it's double.

typedef struct somestruct {     int uniontype     myunion numbers; } mystruct; 

Is there any better solution?

like image 382
tomdavies Avatar asked May 18 '13 10:05

tomdavies


People also ask

How do you determine a union type?

To check if a string is in a union type:Create a reusable function that takes a string as a parameter. Add the values of the union type of an array. Use the includes() method to check if the string is contained in the array.

How do you know which variable from union is used or accessed?

There is no way to tell. You should have some additional flags (or other means external to your union) saying which of the union parts is really used.

Is union a type?

In other words, a union type definition will specify which of a number of permitted primitive types may be stored in its instances, e.g., "float or long integer". In contrast with a record (or structure), which could be defined to contain a float and an integer; in a union, there is only one value at any given time.

What is the size of this union?

When we declare a union, memory allocated for the union is equal to memory needed for the largest member of it, and all members share this same memory space. Since u is a union, memory allocated to u will be max of float y(4 bytes) and long z(8 bytes). So, total size will be 18 bytes (10 + 8).


2 Answers

Is there any better solution?

No, the solution that you showed is the best (and the only) one. unions are pretty simplistic - they do not "track" what you've assigned to what. All they do is let you reuse the same memory range for all their members. They do not provide anything else beyond that, so enclosing them in a struct and using a "type" field for tracking is precisely the correct thing to do.

like image 63
Sergey Kalinichenko Avatar answered Sep 27 '22 18:09

Sergey Kalinichenko


C does not automatically keep track of which field in a union is currently in use. (In fact, I believe reading from the "wrong" field results in implementation defined behavior.) As such, it is up to your code to keep track of which one is currently used / filled out.

Your approach to keeping a separate 'uniontype' variable is a very common approach to this, and should work well.

like image 20
Eric Pi Avatar answered Sep 27 '22 19:09

Eric Pi