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
Short answer: c provides no syntaxtical help for that at all.
Good news: You can support polymorphism in c by using function pointers.
There are many questions explaining how to do that already present on Stack Overflow. In a minute I’ll edit in a link or two…Not liking the answer that I found for this use, so here goes.
For each operation, write a set of functions that take all legal combinations of types. Each one does exactly one combination, so it is easy. Then construct a table of function pointers like this
And now your general add function determines the two types it has and calls the right function by indexing into the table.