如何定义不支持输入参数的宏function,同时支持输入参数

我想定义一个同时支持的宏函数:

1)没有输入参数

2)输入参数

有点像:

#define MACRO_TEST(X)\ printf("this is a test\n");\ printf("%d\n",x) // the last printf should not executed if there is no input parameter when calling the macro 

主要:

 int main() { MACRO_TEST(); // This should display only the first printf in the macro MACRO_TEST(5); // This should display both printf in the macro } 

您可以使用sizeof来实现此目的。

考虑这样的事情:

 #define MACRO_TEST(X) { \ int args[] = {X}; \ printf("this is a test\n");\ if(sizeof(args) > 0) \ printf("%d\n",*args); \ } 

gcc和最新版本的MS编译器支持可变参数宏 – 即与printf类似的宏。

gcc文档: http : //gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html

Microsoft文档: http : //msdn.microsoft.com/en-us/library/ms177415(v = vs.80).aspx

不完全是这样,但……

 #include  #define MTEST_ #define MTEST__(x) printf("%d\n",x) #define MACRO_TEST(x)\ printf("this is a test\n");\ MTEST_##x int main(void) { MACRO_TEST(); MACRO_TEST(_(5)); return 0; } 

编辑

如果0可以用作跳过:

 #include  #define MACRO_TEST(x) \ do { \ printf("this is a test\n"); \ if (x +0) printf("%d\n", x +0); \ } while(0) int main(void) { MACRO_TEST(); MACRO_TEST(5); return 0; } 

C99标准说,

除非第二个定义是类似于对象的宏定义且两个替换列表相同,否则当前定义为类似对象的宏的标识符不应由另一个#define重新处理指令重新定义。 同样,当前定义为类函数宏的标识符不应由另一个#define预处理指令重新定义,除非第二个定义是具有相同数字和参数拼写的类函数宏定义,并且两个替换列表相同。

我认为编译器会提示重新定义MACRO的警告。 因此,这是不可能的。