i have struct union inside it, shown below
typedef struct { type_e type; union { char m_char; int m_int; // more types. on 27 types special types } my_data; } data_t; this struct used develop algorithms, including singular value decomposition (svd) inside function/method. however, every-time need access element of union, have use switch (over 10 switch() used svd). based on limited understanding, @ each instance of time, union members hold same value. can use char member , cast different types? example:
data_t ldata; // initialize ldata values int x = (int)(ldata.my_data.m_char). and how work casting pointers?
even casting, still needs use switch in cases. there way avoid using switch? tried using different struct format (as explained in declare generic variable type ), , looks using union more readable. previously, didn't think on :(
this example mentioned in previous post, has similar example of switch
void vector(data_t *vec, uint32_t start_element, uint32_t end_element) { uint32_t i; // check *vec not null if (!vec) { // write error } data_t x; (i =start_element; <= 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; } } }
since joined so, don’t have reputations add comments yet. adding answer:
from see, if want type cast it, have stated in question, in position know type (int or char). in case, can directly access m_int , hence there no need switch or cast.
so either follow approach of using union or using (void *) noted in other answer
Comments
Post a Comment