C 中的宏条件语句

Macro conditional statements in C

是否可以在 C 的宏函数中实现条件宏。像这样:

#define fun(x)
#if x==0
    fun1;
#else
    fun2;
#endif

#define fun1 // do something here
#define fun2 // do something else here

换句话说,预处理器根据参数值决定使用哪个宏。

fun(0) // fun1 is "preprocessed"
fun(1) // fun2 is "preprocessed"

我知道这个例子行不通,但我想知道是否有可能让它以某种方式工作?

男.

您不能在预处理器指令中使用预处理器条件。例如,您可以在此处找到背景和解决方法:How to use #if inside #define in the C preprocessor? and Is it possible for C preprocessor macros to contain preprocessor directives?

不过,您可以做:

#include <stdio.h>

#define CONCAT(i) fun ## i() /* For docs on this see here:
                                https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html */
#define fun(i) CONCAT(i)

void fun1(void)
{
  puts(__FUNCTION__);
}

void fun2(void)
{
  puts(__FUNCTION__);
}


int main(void)
{
  fun(1);
  fun(2);
}

这将导致:

...

int main(void)
{
  fun1();
  fun2();
}

正在传递给编译器并打印:

fun1
fun2

您可以通过以下方式进一步混淆您的代码:

... 

#define MYZERO 1
#define MYONE 2

int main(void)
{
  fun(MYZERO);
  fun(MYONE);
}

导致相同的代码被传递给编译器。