Macros With a Variable Number of Arguments
C语言宏定义,使用可变参数。
#define debug(format, ...) fprintf (stderr, format, __VA_ARGS__) #define debug(format, args...) fprintf (stderr, format, args)
上述的宏定义是存在问题的。当没有可变参数输入时,需要用##,预处理会去掉comma。
#define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__) #define debug(format, args...) fprintf (stderr, format, ##args)
#include#define debug_fix(format, args...) fprintf (stderr, format, ##args) #define debug(format, args...) fprintf (stderr, format, args) int main() { debug("hellon"); debug_fix("hellon"); return 0; } //gcc -E macro_var.c -o macro_var.i 31 # 6 "macro_var.c" 732 int main() 733 { 734 fprintf ( 735 # 8 "macro_var.c" 3 4 736 stderr 737 # 8 "macro_var.c" 738 , "hellon", ); //NOK 739 fprintf ( 740 # 9 "macro_var.c" 3 4 741 stderr 742 # 9 "macro_var.c" 743 , "hellon"); //OK 744 return 0; 745 }



