# 用来把参数转换成字符
#include <stdio.h>
#define FUN(X) (printf("%s=%d\n",#X,X)) /* #用来把参数转换成字符 */
int test(int argc, char ** argv)
{
int a = 1;
int b = 2;
FUN(a);
FUN(b);
FUN(a+b);
return 0;
}
/** 程序输出结果:
*******************************
a=1
b=2
a+b=3
*******************************
*/
#include <stdio.h>
#include <stdlib.h>
#define STR(x) #x
int main(int argc, char *argv[])
{
printf(STR(vck));
printf("\r\n");
return 1;
}
/*
输出结果:vck
*/
## 把两个语言符号组合成单个语言符号
#include <stdio.h>
#define XNAME(n) x##n /* ## 这个运算符把两个语言符号组合成单个语言符号*/
#define PXN(n) printf("x"#n" = %d\n",x##n)
int main(int argc, char ** argv)
{
int XNAME(1) = 10886; /*宏展开就是:x1 = 10086*/
PXN(1); /*宏展开就是:printf("x1 = %d\n",x1) */
return 0;
}
/** 程序输出结果:
*******************************
x1 = 10886
*******************************
*/
#include <stdio.h>
#include <stdlib.h>
#define CONS(a,b) (int)(a##e##b)
int main(int argc, char *argv[])
{
printf("%d\r\n", CONS(2, 3));
return 1;
}
/*
输出结果:2000
*/
__VA_ARGS__ 和 ##__VA_ARGS__
#include "stdio.h"
#define DEBUG1(format, ...) do{ \
printf(format, __VA_ARGS__); \
\
} while(0)
#define DEBUG2(format, args...) do{ \
printf(format, ##args); \
\
} while(0)
#define DEBUG3(format, ...) do{ \
printf(format, ##__VA_ARGS__); \
\
} while(0)
int
main(int argc, char **argv)
{
printf("hello world.1 \n");
//DEBUG1("hello world.2\n");//错误 参数为零
DEBUG1("hello world.2 %d %d\n", 1, 2);
DEBUG2("hello world.3\n");
DEBUG2("hello world.3 %d %d %d\n", 1, 2, 3);
DEBUG3("hello world.4\n");
DEBUG3("hello world.4 %d %d %d %d\n", 1, 2, 3, 4);
return 0;
}
应用
#include "stdio.h"
#define DEBUG_ON
#ifdef DEBUG_ON
#define DEBUG(format, ...) do{ \
printf("File:%s, Line:%d, "format"", __FILE__, __LINE__, ##__VA_ARGS__); \
\
} while(0)
#else
#define DEBUG(format, ...)
#endif
int
main(int argc, char **argv)
{
DEBUG("hello world %d %d\n", 1, 2);
return 0;
}
/**程序输出结果:
***********************************************************
File:E:\C Language\printf.c, Line:19, hello world 1 2
***********************************************************
*/
总结
- #用来把参数转换成字符.
- ##这个运算符把两个语言符号组合成单个语言符号
- __VA_ARGS__ 是一个可变参数的宏,实现思想就是宏定义中参数列表的最后一个参数为省略号(也就是三个点)。
- __VA_ARGS__ 宏前面加上 ## 的作用在于,当可变参数的个数为 0 时,这里的 ## 起到把前面多余的逗号 , 去掉的作用,否则会编译出错。
- 注意宏定义连接符 \ 后面不要有任何操作,直接回车,下一行的前面可以有空格。