gpt4 book ai didi

c - C 中的宏条件语句

转载 作者:行者123 更新时间:2023-12-04 12:26:26 25 4
gpt4 key购买 nike

是否可以在 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"

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

M。

最佳答案

您不能在预处理器指令中使用预处理器条件。您可以在此处找到的背景和解决方法:How to use #if inside #define in the C preprocessor?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);
}

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

关于c - C 中的宏条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40947811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com