我可以使用C预处理器有条件地检查宏的值吗?

时间:2022-11-25 10:53:15

I know I can use the C preprocessor to conditionally compile something like:

我知道我可以使用C预处理器有条件地编译如下:

#define USESPECIALFEATURE

#if defined USESPECIALFEATURE
usespecialfeature();
#endif

But I am wondering if I can do something like this:

但我想知道我能不能做这样的事情:

#define USEDFEATURE 4

#if defined USEDFEATURE == 4
usefeature(4);
#endif

In other words, I want to use the preprocessor to check the value of a particular macro definition. This doesn't work when I tried it.

换句话说,我想使用预处理器检查特定宏定义的值。我试的时候没用。

2 个解决方案

#1


8  

Absolutely:

绝对的:

#define MACRO 10

#if MACRO == 10
enable_feature(10);
#endif

Drop the define statement, as it checks whether a macro is defined, not whether the macro has a specific value.

删除define语句,因为它检查是否定义了宏,而不是宏是否具有特定的值。

You can use a variety of arithmetics, too:

你也可以使用各种算术:

#if MACRO > 10
#if MACRO < 10
#if MACRO + ANOTHER > 20
#if MACRO & 0xF8
#if MACRO^ANOTHER
#if MACRO > 10 && MACRO < 20

... and chain the conditionals:

…和连锁条件:

#if MACRO == 1
enable_feature(1);
#elif MACRO == 2
enable_feature(2);
#endif

#2


4  

Your idea is possible, but you are using it wrong.

你的想法是可能的,但你错了。

#define YOUR_MACRO    3

#if YOUR_MACRO == 3
    do_job(3);
#endif

No defined check if you want to compare with value. If your macro is not defined, it evaluates to 0 on #if check:

如果您想要与值进行比较,则没有定义检查。如果您的宏没有定义,它在#上的值为0,如果检查:

#if NOT_DEFINED_MACRO
do_something();
#endif

Code above is equal to:

以上代码等于:

#if 0
do_something();
#endif

#1


8  

Absolutely:

绝对的:

#define MACRO 10

#if MACRO == 10
enable_feature(10);
#endif

Drop the define statement, as it checks whether a macro is defined, not whether the macro has a specific value.

删除define语句,因为它检查是否定义了宏,而不是宏是否具有特定的值。

You can use a variety of arithmetics, too:

你也可以使用各种算术:

#if MACRO > 10
#if MACRO < 10
#if MACRO + ANOTHER > 20
#if MACRO & 0xF8
#if MACRO^ANOTHER
#if MACRO > 10 && MACRO < 20

... and chain the conditionals:

…和连锁条件:

#if MACRO == 1
enable_feature(1);
#elif MACRO == 2
enable_feature(2);
#endif

#2


4  

Your idea is possible, but you are using it wrong.

你的想法是可能的,但你错了。

#define YOUR_MACRO    3

#if YOUR_MACRO == 3
    do_job(3);
#endif

No defined check if you want to compare with value. If your macro is not defined, it evaluates to 0 on #if check:

如果您想要与值进行比较,则没有定义检查。如果您的宏没有定义,它在#上的值为0,如果检查:

#if NOT_DEFINED_MACRO
do_something();
#endif

Code above is equal to:

以上代码等于:

#if 0
do_something();
#endif