宏定义printf中#的使用
来源:岁月联盟
时间:2011-12-12
#进行宏字符串连接,在宏中把参数解释为字符串,不可以在语句中直接使用。在宏定义中
printf("%s;/n", #S) 会被解释为
printf("%s;/n", "S")
例如下面的代码
#define TRACE(S) (printf("%s/n", #S), S) /*注意用逗号而不是分号*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int a=5;
int b=TRACE(a);
const char *str="hello";
char des[50];
strcpy(des,TRACE(str));
puts(des);
system("pause");
return 0;
}
同时宏定义又是一个逗号表达式 ,所以拷贝到des里面的值为后面S也就是str的值。
注意:
int a=printf("%s;/n", "S"),a等于printf的返回值,也就是printf打印的字符个数。
摘自 何昊专栏 程序员面试500问