For some testing purposes, I need to compare two unions to see if they are identical. Is it enough to compare all members one by one?
union Data {
int i;
float f;
char* str;
} Data;
bool isSame(union Data left, union Data right)
{
return (left.i == right.i) && (left.f == right.f) && (left.str == right.str);
}
My hunch is that it could fail if one the unions has first contained a larger type and then switched to a smaller type. I have seen some suggestions mentioning wrapping the union in a struct (like here: What is the correct way to check equality between instances of a union?) which keeps track of which data type that the union currently is, but I don't see how that would practically be implemented. Would I not need to manually set the union type in every instance where I set the union value?
struct myData
{
int dataType;
union {
...
} u;
}
void someFunc()
{
struct myData my_data_value = {0};
my_data_value.u.i = 5;
my_data_value.u.dataType = ENUM_TYPE_INTEGER;
my_data_value.u.f = 5.34;
my_data_value.u.dataType = ENUM_TYPE_FLOAT;
...
}
It does not seem warranted to double all code where my union is involved simply to be able to make a perfect comparison of the union values. Am I missing some obvious smart way to go about this?