C语言 C 宏中的#x 是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14351971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does #x inside a C macro mean?
提问by Anders Lind
For example I have a macro:
例如我有一个宏:
#define PRINT(int) printf(#int "%d\n",int)
I kinda know what is the result. But how come #int repersent the whole thing?
我有点知道结果是什么。但是为什么#int 代表了整个事情?
I kinda forget this detail. Can anybody kindely give me a hint?
我有点忘记这个细节了。任何人都可以给我一个提示吗?
Thanks!
谢谢!
回答by metamatt
In this context (applied to a parameter reference in a macro definition), the pound sign means to expand this parameter to the literal text of the argument that was passed to the macro.
在此上下文中(应用于宏定义中的参数引用),井号表示将此参数扩展为传递给宏的参数的文字文本。
In this case, if you call PRINT(5)the macro expansion will be printf("5" "%d\n", 5);which will print 5 5; not very useful; however if you call PRINT(5+5)the macro expansion will be printf("5+5" "%d\n", 5+5);which will print 5+5 10, a little less trivial.
在这种情况下,如果你调用PRINT(5)宏扩展将是printf("5" "%d\n", 5);which will print 5 5; 不是很有用;但是,如果您调用PRINT(5+5)宏扩展将是printf("5+5" "%d\n", 5+5);which will print 5+5 10,那么就不那么琐碎了。
This very example is explained in this tutorial on the C preprocessor(which, incidentally, is the first Google hit for c macro pound sign).
这个例子在这个关于 C 预处理器的教程中进行了解释(顺便说一句,这是第一个谷歌对c 宏英镑符号的命中)。
回答by Hyman Peking
"#" can show the name of a variable, it's better to define the macro as this:
"#" 可以显示变量的名称,最好这样定义宏:
#define PRINT(i) printf(#i "= %d\n", i)
and use it like this:
并像这样使用它:
int i = 5;
PRINT(i);
Result shown:
结果显示:
i = 5
回答by Karthik T
That is a bad choice of name for the macro parameter, but harmless (thanks dreamlax).
这是宏参数名称的错误选择,但无害(感谢 Dreamlax)。
Basically if i write like so
基本上如果我这样写
PRINT(5);
It will be replaced as
它将被替换为
printf("5" "%d\n",5);
or
或者
printf("5 %d\n",5);
It is a process called Stringification, #int is replaced with a string consisting of its content, 5 -> "5"
这是一个名为Stringification的过程,#int 被替换为其内容组成的字符串,5 -> "5"

