Converting struct into a char
I have a problem where I need to convert a the name of a struct variable into a char
. For example:
struct CARINFO a;
When my function takes an argument of CARINFO a
, I want to use 开发者_开发问答both a
and "a"
in the function.
Can anyone help?
You can use a macro to pass both the pointer to your struct and its name to the actual function.
struct bar {
// blah
};
void actual_foo(struct bar *b, char *bname) {
// whatever
}
#define foo(bar) actual_foo(&(bar), #bar)
int main() {
struct bar b;
foo(b);
}
The best you can do in C is to use a single macro to define both the string and the variable. There's no runtime inspection that would allow you to rediscover the name of a variable.
You could do it by making the function into a macro, and using the # operator (stringification) to get the name of hte argument.
For example:
#define MYFUNC(x) \
do { real_func(x); printf("parameter name: " #x "\n"); } while (0)
精彩评论