Is it possible to pass variable type as part of a function parameter, e.g.:
void foo(varType t开发者_StackOverflow中文版ype)
{
// Cast to global static
unsigned char bar;
bar = ((type *)(&static_array))->member;
}
I remember it has something to do with GCC's typeof
and using macros?
You could make an enum for all different types possible, and use a switch to make the dereferencing:
typedef enum {
CHAR,
INT,
FLOAT,
DOUBLE
} TYPE;
void foo(TYPE t, void* x){
switch(t){
case CHAR:
(char*)x;
break;
case INT:
(int*)x;
break;
...
}
}
You can't do that for a function, because then it needs to know the types of the arguments (and any other symbols the function uses) to generate working machine code. You could try a macro like:
#define foo(type_t) ({ \
unsigned char bar; \
bar = ((type_t*)(&static_array))->member; \
... \
})
Eh, of course you can. Just use a macro like so:
#include <stdio.h>
#define swap(type, foo, bar) ({type tmp; tmp=foo; foo=bar; bar=tmp;})
int main() {
int a=3, b=0;
swap(int, a, b); //
精彩评论