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.
Preprocessor conditionals can test arithmetic expressions, or whether a name is defined as a macro, or both simultaneously using the special defined operator. A conditional in the C preprocessor resembles in some ways an if statement in C, but it is important to understand the difference between them.
Inside of a C source file, you can use the #ifdef macro to check if a macro is defined.
There is no way you can test whether a defined macro has a value. You can only test whether a specific value matches the value of a macro. Any macro name that you define should always have a value, or it should never have a value.
Conditional Compilation: Conditional Compilation directives help to compile a specific portion of the program or let us skip compilation of some specific part of the program based on some conditions. In our previous article, we have discussed about two such directives 'ifdef' and 'endif'.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With