I am trying to declare a generic variable type in C (I can't us C++), and I have in my mind the following options.
Option1
typedef struct
{
void *value;
ElementType_e type;
} Data_t;
Option 2
typedef struct {
ElementType_e type;
union {
int a;
float b;
char c;
} my_union;
} my_struct;
where ElementType_e is an enum that holds all the possible type of variables (e.g. int, char, unsigned int, etc..). I am kinda leaning toward option 1, because I don't believe casting will add extra computational time, compared to switch, right?
I am just wondering which type is more useful? I know option 1 will require casting every-time being used/accessed. is there any possible issues that could happen with casting ( especially with running/compiling the code on different platform, e.g 32 bits and 16 bits micro)
While option2 require a switch () to do any operation (e.g. addition, ...).
The following link explained that Option 2 is better ( from readability point of view), but i mainly concern about the code size and computational cost. Generic data type in C [ void * ]
is there any possible issues that could happen with casting
No, as you do not want cast, as there is no need to cast when assigning from/to a void
-pointer (in C).
I am just wondering which type is more useful?
Both do, so it depends, as
ElementType_e
).Referring a comment:
Regarding performance I expect no major difference between both approaches (if implemented sanely), as both options need condtional statments on assigning to/from (exception here are pointer variables, which for option 1 go without conditonal statements for assignment).
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