Hi I am working on small parser and "equation solver" in C, part of this process is to do arithmetical operations on tokens. Each token contains void* pointer to numerical data, and enum, which defines type of data.
This is example of the function, which creates new token by adding two others tokens. In order to do so, I need to
- check type
- cast
- do operation
- create new token from result
a
Token* _CreateTokenByAddition(Token* arg1, Token* arg2){
Token *tokenResult;
if ((arg1->_type == tk_IntData) && (arg2->_type == tk_IntData)){
int* intResult = malloc(sizeof(int));
*intResult = *(int*)arg1->_data + *(int*)arg2->_data;
tokenResult = CreateTokenFromValue(intResult, tk_IntData);
}else
if ((arg1->_type == tk_IntData) && (arg2->_type == tk_FloatData)){
float* intResult = malloc(sizeof(float));
*intResult = *(int*)arg1->_data + *(float*)arg2->_data;
tokenResult = CreateTokenFromValue(intResult, tk_FloatData);
}else
if ((arg1->_type == tk_FloatData) && (arg2->_type == tk_IntData)){
float* intResult = malloc(sizeof(float));
*intResult = *(float*)arg1->_data + *(int*)arg2->_data;
tokenResult = CreateTokenFromValue(intResult, tk_FloatData);
}
else
if ((arg1->_type == tk_FloatData) && (arg2->_type == tk_FloatData)){
float* intResult = malloc(sizeof(float));
*intResult = *(float*)arg1->_data + *(float*)arg2->_data;
tokenResult = CreateTokenFromValue(intResult, tk_FloatData);
}
return tokenResult;
}
I have almost identical functions for -, *, /. And I will probably need to create more.
Questions are: how I can create one generic function which will support all simple operations such as +-*/ ? I dont want to put this function in macro and then duplicate it 4 times by replacing mathematical operand. Any way how I can simplify data type checks and casts from void pointers?
Any way I can make this code, better ?
Assumption: I dont have any non numerical data types (eg strings)
Thanks
Cool, thanks a lot for these replies, I see what you mean by function pointers. I am going to think about it and use one of these methods. Thanks