I have a struct with union inside it, as shown below
typedef struct {
Type_e type;
union {
char m_char;
int m_int;
// more types. over 27 types with special types
} my_data;
} Data_t;
This struct is used to develop algorithms, including singular value decomposition (SVD) inside a function/method. However, every-time I need to access an element of the union, I have to use switch (over 10 switch() will be used for SVD). based on my limited understanding, at each instance of time, all union members hold the same value. Can I use the char member and cast it to the different types? For example:
Data_t lData;
// initialize lData with some values
int x = (int)(lData.my_data.m_char).
and How will this work for casting pointers?
even with casting, I still needs to use switch in some cases. is there a way to avoid using switch? I tried using different struct format (as explained in Declare generic variable type ), and it looks using union is more readable. Previously, I didn't think is over :(
this example was mentioned in previous post, which has a similar example of switch
void vector(Data_t *vec, UInt32_t start_element, UInt32_t end_element)
{
UInt32_t i;
// check *vec is not null
if (!vec)
{
// Write error
}
Data_t x;
for (i =start_element; i <= end_element; i++)
{
switch (vec[i].type)
{
case UINT32: x.my_data.m_int = vec[i].my_data.m_int; break;
// more possible cases
default:
break;
}
}
}