C 语言 define 变参__VA_ARGS__使用(转)
在C语言的标准库中,printf、scanf、sscanf、sprintf、sscanf这些标准库的输入输出函数,参数都是可变的。在调试程序时,我们可能希望定义一个参数可变的输出函数来记录日志,那么用可变参数的宏是一个不错的选择。 在C99中规定宏也可以像函数一样带可变的参数,如: #define LOG(format,...) fprintf(stdout,format,__VA_ARGS__)
? 其中,...表示可变参数列表,__VA_ARGS__在预处理中,会被实际的参数集(实参列表)所替换。 #define LOG(format,args...) fprintf(stdout,args)
? 同样,args在预处理过程中,会被实际的参数集所替换。其用法和上面的方式一样,只是参数的符号有变。 #define LOG(format,##__VA_ARGS__) #define LOG(format,##args) ? 即然参数可以省略,那么用宏定义一个开关,实现一个输出日志的函数就简单了: #ifdef DEBUG #define LOG(format,">>>>>" format "<<<<",##__VA_ARGS__) #else #define LOG(format,...) #endif ? example#include "stdio.h" #define LOG_TYPE1(format,...) do{ printf(format,__VA_ARGS__); } while(0) #define LOG_TYPE2(format,args...) do{ printf(format,args); } while(0) #define LOG_TYPE3(format,##__VA_ARGS__); } while(0) #define LOG_TYPE4(format,##args); } while(0) #define LOG(x) printf("LOG "#x" %d n",x); int value = 10; int main() { printf("hello world. n"); //LOG_TYPE1("hello %d n"); error LOG_TYPE1("hello %d n",1); //LOG_TYPE2("hello n"); error LOG_TYPE2("hello %d n",2); LOG_TYPE3("hello 3n"); LOG_TYPE3("hello %dn",3); LOG_TYPE4("hello 4n"); LOG_TYPE4("hello %dn",4); LOG(10); LOG(value); return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |