What do you guys think is a good way to deal with this situation:
#define TYPE_INT 0 // 4 byte, signed
#define TYPE_CHAR 1 // 1 byte, signed
#define TYPE_UINT 2 // 4 byte, unsigned
#define TYPE_FLOAT 3 // 4 byte, signed, floating point
typedef struct {
float Value; // This value can be of any type, but initially stored in a float
int Type;
} AnyVal;
void main() {
// The value is loaded by some function, it can have a value of any type in it
AnyVal *Val = LoadVal();
// Now do some math with that value
switch (AnyVal->Type[0]) {
case TYPE_INT: ((int)(AnyVal->Value)) /= 2; break;
case TYPE_UINT: ((unsigned int)(AnyVal->Value)) /= 2; break;
case TYPE_CHAR: ((char)(AnyVal->Value)) /= 2; break;
case TYPE_FLOAT: AnyVal->Value /= 2; break;
}
// Now send it back with the math done
ValContinueProcessing(Val);
}
Basically I have a structure that can hold a value which can be one a several types, and that type is stored in an integer defined by a series of macro's. While this code seems kind of useless in this context, it has a significant meaning to the code I am working on. The problem is that doing math on this value requires checking for the type and performing the same math with the only difference being the type name.
Is there a way I could do something like this instead?
switch (AnyVal->Type[0]) {
case TYPE_INT: MAGICTYPE = int; break;
case TYPE_UINT: MAGICTYPE = unsigned int; break;
case TYPE_CHAR: MAGICTYPE = char; break;
case TYPE_FLOAT: MAGICTYPE = float; break;
}
((MAGICTYPE)(AnyVal->Value)) /= 2;
...Or use a macro or something? Problem with macro's is that it resolves at compile time, and this needs to be done at runtime.
I would much rather write the math once and create a switch for the type, instead of copying the math over and over just to change the type name. In my application, the math is quite complex, and I am having to repeat it more times than I would like, but I can't think of a better solution.
And as much as I cringe at the thought of using compiler extensions, id use it if it can solve this problem. I am using the gcc compiler, latest build.