c - 是否可以使用 #if 到 mcro 函数中检查宏参数

标签 c macros

我想这样开发一个宏

#define MACRO_TEST(a, MM, MN) \
#if MM == 1
    printf("MM "); \
#endif
#if MN == 1
    printf("MN "); \
#endif
    printf("%d\n",a);


main()
{
   MACRO_TEST(4, 1, 1); // output should be: MM MN 4
   MACRO_TEST(4, 1, 0); // output should be: MM 4
   MACRO_TEST(4, 0, 1); // output should be: MN 4
   MACRO_TEST(4, 0, 0); // output should be: 4
}

在 C 中可以这样做吗?

什么是正确的方法?因为上面的代码产生了构建错误

最佳答案

您不需要使用 #if,经典的 if 语句就可以正常工作。

此外,在您的示例中,宏的使用似乎并不是真正合理的:为什么您不使用简单的函数?

void test(int a, int mm, int mn)
{
    if(mm == 1)
        printf("MM ");
    if(mn == 1)
       printf("MN ");
    printf("%d\n", a);

    return;
}

关于c - 是否可以使用 #if 到 mcro 函数中检查宏参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21556758/

相关文章:

C-X11 API : Custom Control Redraw Issue

c - 如何使用 GNU C 预处理器预定义宏?

c - 使用下划线作为宏函数的参数

c - 如何解释 C 中结构的成员访问(点)运算符?

c - 为什么会出现段错误+如何消除它?

c++ - 如何在 iPhone 上使用 LAME 编码为 .mp3 时显示进度条?

c - 如何判断当前目录是否为 C 的根目录?

c - 正则表达式谜题 : encapsulated structures

在主体中定义 name_fn 的函数的 C 原型(prototype)

gcc - 预处理器输出