[英]What does #x inside a C macro mean?
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!谢谢!
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);
在这种情况下,如果您调用
PRINT(5)
宏扩展将是printf("5" "%d\n", 5);
which will print 5 5
;这将打印
5 5
; not very useful;不是很有用; however if you call
PRINT(5+5)
the macro expansion will be printf("5+5" "%d\n", 5+5);
但是,如果您调用
PRINT(5+5)
宏扩展将是printf("5+5" "%d\n", 5+5);
which will print 5+5 10
, a little less trivial.这将打印
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 宏磅符号)。
"#" 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
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"
'#' is called a stringize operator. '#' 称为字符串化运算符。 Stringize operator puts quotes around the parameter passed and returns a string.
Stringize 运算符在传递的参数周围加上引号并返回一个字符串。 It is only used in a marco statements that take the arguments.
它仅用于带参数的 marco 语句中。
#include<stdio.h>
#define stringLiteral(sl) #sl
int main()
{
char StringizeOpreator = 'a';
printf(stringLiteral(StringizeOpreator));
return 0;
}
Here the stringLiteral
marco takes the formal argument sl
and returns #sl
.这里
stringLiteral
marco 接受形式参数sl
并返回#sl
。 Actual argument passed is StringizeOpreator
variable.传递的实际参数是
StringizeOpreator
变量。 The return statement #sl
has #
operator, that puts quotes around the argument like "StringizeOpreator"
and returns a string. return 语句
#sl
有#
运算符,它在参数周围加上引号,如"StringizeOpreator"
并返回一个字符串。
So the output of the above program is the name of the actual parameter 'StringizeOpreator' rather than the value stored in the actual parameter passed.所以上述程序的输出是实参'StringizeOpreator'的名称,而不是传递的实参中存储的值。
output :
StringizeOperator
...
exitcode 0
To learn more visit this link: Stringize Operator要了解更多信息,请访问此链接: 字符串化运算符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.