0
点赞
收藏
分享

微信扫一扫

可变参数宏

#include <stdio.h>  

#define __DEBUG__

#ifdef __DEBUG__
#define DEBUG(format, ...) printf("文件:"__FILE__ "\n行号:%d\n输出:"format"\n", __LINE__, ##__VA_ARGS__)
#else
#define DEBUG(format, ...)

#endif

int main(int argc, char **argv) {
char str[] = "Hello World";
float a = 889.5;
DEBUG("A ha, check me: %s %.2f", str, a);
return 0;
}

运行测试输出结果:

行号:18
输出:A ha, check me: Hello World 889.50

原始的测试行:

#define DEBUG(format,...) printf("File: "__FILE__"\nLine: %05d \n"format"\n", __LINE__, ##__VA_ARGS__)

​%05d​​​ 输出占 5 格,前面不足的,补零. 如果​​%5d​​,占 5 格,不足的空格.

​format​​​ 参数名, 前后相同就行了,​​__VA_ARGS__​​​是可变参数宏, 宏参数对应前面的三个点(省略号), ​​##​​​的意思是,如果可变参数(​​format​​​, 就是后面的​​%s​​​)被忽略或为空,将使预处理器(​​preprocessor​​ )去除掉它前面的那个逗号

​__LINE__​​​:在源代码中插入当前源代码行号;
​​​__FILE__​​:在源文件中插入当前源文件名;

另外: ​​...​​​只能放最后.
经测试, ​​​format​​​ 只能放第一个逗号前, 且挨着逗号,​​...​​​和对应的​​_VA_ARGS_​​只能放在最后




举报

相关推荐

0 条评论