Can I conditionally check the value of a macro using the C preprocessor?

Viewed 2476

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

#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 Answers

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.

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

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:

#if NOT_DEFINED_MACRO
do_something();
#endif

Code above is equal to:

#if 0
do_something();
#endif
Related