C语言--#、##、__VA_ARGS__ 和##__VA_ARGS__ 的使用
# 用来把参数转换成字符
-
#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
-
*******************************
-
*/
-
2、## 把两个语言符号组合成单个语言符号
-
#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
-
*******************************
-
*/
-
-
3、__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
-
***********************************************************
-
*/
1、#用来把参数转换成字符.
2、##这个运算符把两个语言符号组合成单个语言符号
3、 __VA_ARGS__ 是一个可变参数的宏,实现思想就是宏定义中参数列表的最后一个参数为省略号(也就是三个点)。
4、##__VA_ARGS__ 宏前面加上##的作用在于,当可变参数的个数为0时,这里的##起到把前面多余的","去掉的作用,否则会编译出错。
5、注意宏定义连接符 \ 后面不要有任何操作,直接回车,下一行的前面可以有空格。
======================================================-=============================================
为更好了解C/C++中可变参数的知识,我从网上摘录了两篇文章,算是自己的一个总结。本篇主要是关于“## __VA_ARGS__”宏的介绍和使用。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」