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?
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.
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.
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.
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).
Is there any better solution?
No, the solution that you showed is the best (and the only) one. union
s 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.
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.
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