This is not a 'How can a mixed data type (int, float, char, etc) be stored in an array?' question read carefully please! Suppose I have the following void pointer, something I don't know it's type until runtime:
void* data;
now I know I can do the following, when I know the type of data
(e.g. int
):
int typed_data = *(int*)data;
using a switch case
statement I could check a variable to determine which cast to perform:
switch(type_id) {
case INT:
int typed_data = *(int*)data;
break;
case FLOAT:
float typed_data = *(float*)data;
break;
// ...
// etc.
}
But, this way I will not be able to access typed_data outside the switch block, consider the below funstion as an example; It takes two void pointers, and according to the value of type_id
, it casts the s
and x
to correct data types, and then does other things with the newly defined typed data:
int sequential_seach(int n, void* s, void* x, type_id) {
int location = 0;
switch(type_id) {
case INT:
int *list = s;
int element = *(int*)x;
break;
case FLOAT:
float *list = s;
float element = *(float*)x;
break;
// ...
// etc.
}
while(location < n && list[location] != element) { // <---This will cause a compile error
location++;
if(location > n - 1) {
location = -1;
}
}
return location;
}
In the above function location
and list
are not accessible outside the swtich
block, even if type_id matched one of the case
values and they were defined, they are still out of scope, outside the switch
block, therefore when the compiler reaches the line while
resides, it complains that location
and list
are not defined. But these typed variables are needed for the function. So how to solve this? should I copy paste the while
block into every case
? That doesn't look it's a very good solution. What if I had a longer code which needed these variables in 100 different places?