Can I do something like this? I would like to use data types instead of constants in my enum type_t.
typedef struct {
char id;
long data;
} type1_t;
typedef struct {
char id;
long data;
float moredata;
} type2_t;
typedef enum {
type1_t, type2_t
} type_t;
typedef struct {
type_t type;
char* something;
} midas;
midas obj1;
obj1.type = type1_t;
obj1.type.id = 0;
obj1.type.data = 123;
midas obj2;
obj2.type = type2_t;
obj2.type.id = 3;
obj2.type.data = 456;
obj2.type.moredata = 3.14;
In the example the type variable of the midas struct should then refer to type1_t or type2_t. So if I set the type to type2_t, the size of it should be bigger than when I set type1_t.
No, you can’t do that. If you were using C++, you could use templates to achieve this. But there is no “type enum” mechanism in C.
You could consider a union:
This will cause
midas.type1valueandmidas.type2valueto occupy the same memory space. The amount of memory taken for the union will be equal to the amount of memory required to store the largest data type it contains.You would then have to look at
midas.typecodeand consider which union member to use. If you use the wrong one you will wind up with invalid data and this may lead to program crashes, so be careful.