我试图通过定义操作类型来使用#if 宏来调用正确的代码,所以我做了一个非常简单的例子,类似于我想要做的:
#include <stdio.h>
enum{ADD,SUB,MUL};
#define operation ADD
int main()
{
int a = 4;
int b = 2;
int c;
#if (operation == ADD)
c = a+b;
#endif
#if (operation == SUB)
c = a-b;
#endif
#if (operation == MUL)
c = a*b;
#endif
printf("result = %i",c);
return 0;
}
但不幸的是,这不起作用我得到以下
result = 8
...如果我用数字替换操作它工作正常......但我希望它像上面描述的那样工作。任何帮助
最佳答案
预处理器是(在某种程度上)在实际编译器看到代码之前完成的步骤。因此,它不知道枚举或它们的值,因为它们是在预处理之后进行的编译期间设置的。
您根本无法使用枚举来使用预处理器条件编译。
关于使用枚举的 C 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51104981/