我想定义一个同时支持的宏函数:
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
}发布于 2012-12-21 01:23:45
为此,您可以使用sizeof。
考虑一下这样的情况:
#define MACRO_TEST(X) { \
int args[] = {X}; \
printf("this is a test\n");\
if(sizeof(args) > 0) \
printf("%d\n",*args); \
}发布于 2012-12-21 01:26:19
gcc和最新版本的MS编译器支持各种宏-即工作方式类似于printf的宏。
gcc文档:http://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html
微软文档:http://msdn.microsoft.com/en-us/library/ms177415(v=vs.80).aspx
发布于 2012-12-21 05:57:46
不完全是这样但是..。
#include <stdio.h>
#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 <stdio.h>
#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;
}https://stackoverflow.com/questions/13976935
复制相似问题