首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何定义不支持输入参数同时支持输入参数的宏函数

如何定义不支持输入参数同时支持输入参数的宏函数
EN

Stack Overflow用户
提问于 2012-12-21 00:55:43
回答 4查看 1.1K关注 0票数 1

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

1)无入参

2)输入参数

类似这样的东西:

代码语言:javascript
运行
复制
#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

大体上:

代码语言:javascript
运行
复制
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
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-12-21 01:23:45

为此,您可以使用sizeof。

考虑一下这样的情况:

代码语言:javascript
运行
复制
#define MACRO_TEST(X) { \
  int args[] = {X}; \
  printf("this is a test\n");\
  if(sizeof(args) > 0) \
    printf("%d\n",*args); \
}
票数 5
EN

Stack Overflow用户

发布于 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

票数 1
EN

Stack Overflow用户

发布于 2012-12-21 05:57:46

不完全是这样但是..。

代码语言:javascript
运行
复制
#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可以用作跳过:

代码语言:javascript
运行
复制
#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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13976935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档