How to use Macro argument as string literal?

旧城冷巷雨未停 提交于 2019-11-26 13:50:44

问题


I am trying to figure out how to write a macro that will pass both a string literal representation of a variable name along with the variable itself into a function.

For example given the following function.

void do_something(string name, int val)
{
   cout << name << ": " << val << endl;
}

I would want to write a macro so I can do this:

int my_val = 5;
CALL_DO_SOMETHING(my_val);

Which would print out: my_val: 5

I tried doing the following:

#define CALL_DO_SOMETHING(VAR) do_something("VAR", VAR);

However, as you might guess, the VAR inside the quotes doesn't get replaced, but is just passed as the string literal "VAR". So I would like to know if there is a way to have the macro argument get turned into a string literal itself.


回答1:


Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);



回答2:


You want to use the stringizing operator:

#define STRING(s) #s

int main()
{
    const char * cstr = STRING(abc); //cstr == "abc"
}



回答3:


#define NAME(x) printf("Hello " #x);
main(){
    NAME(Ian)
}
//will print: Hello Ian



回答4:


Perhaps you try this solution:

#define QUANTIDISCHI 6
#define QUDI(x) #x
#define QUdi(x) QUDI(x)
. . . 
. . .
unsigned char TheNumber[] = "QUANTIDISCHI = " QUdi(QUANTIDISCHI) "\n";


来源:https://stackoverflow.com/questions/10507264/how-to-use-macro-argument-as-string-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!