I have some C code where I need to do some calculations with an array of data. The data can be either INT or DOUBLE. In order to deal with the different data types, I was thinking of using an if / else
statement and define the pointer holding the data inside that statement:
/* put values into M, depending on data type*/
if (data_type == 2)
{
double *M;
M = somefunction(DOUBLE);
} else {
unsigned int *M;
M = somefunction(UINT16);
}
/* dummy code - usually I do some calculations on M which are data type independent */
for (i=0;i<(10);i++) {
M[i]=0;
}
This leads to scoping problems because M
is not defined outside the if / else
construct:
error: ‘M’ undeclared (first use in this function)
If I move the definition of M
outside the if / else
statement, the code will compile but M
inside the if / else
is a different M
outside.
So I can circumvent the problem by defining two pointers, one double and one int and check everywhere in my code which type I'm dealing with:
double *Mdouble;
unsigned int *Mint;
/* put values into M, depending on data type*/
if (data_type == 2)
{
Mdouble = somefunction(DOUBLE);
} else {
Mint = somefunction(UINT16);
}
/* dummy code - usually I do some calculations on M which are data type independent */
for (i=0;i<(10);i++) {
if (data_type == 2) {
Mdouble[i]=0;
} else {
Mint[i]=0;
}
}
So here's my question:
How can I solve this problem where M
is a double or int, depending on my incoming data? Could I solve this with some kind of pointer to a pointer work around? I don't want to write duplicate code for each case.
EDIT could template functions or overloading of functions solve my problem? I'm flexible regarding a C / C++ specific solution