Variants
In this exercise, you\'ll discover a way of writing generic data
structures in C
: unions
.
Unions
A union can have a large amount of fields, but contain only one at a time. It is declared the same way as a structure, like shown below:
union int_or_string
{
int int_t;
char *str_t;
};
The union can then be used like this:
union int_or_string value;
value.int_t = 12;
printf("The value is now: %i\n", value.int_t);
value.str_t = "acu";
printf("The value is now: %s\n", value.str_t);
The size of an union is the maximum of the size of its members.
Consequently, the following union\'s size will be sizeof(int64_t)
, 8
bytes.
union integer
{
int8_t smallest;
int16_t small;
int32_t big;
int64_t biggest;
};
Tagged unions
Since there is no way to know which field was last assigned to a union, we have to add a tag to know the stored type.
Taking our previous union, we could write:
enum integer_values
{
smallest,
small,
big,
biggest
};
struct variant
{
enum integer_values tag;
union integer value;
};