Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 596
Zebrafish Avatar asked Nov 24 '17 05:11

Zebrafish


People also ask

What is conditional macro in C?

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.

How do you check if a macro is defined in C?

Inside of a C source file, you can use the #ifdef macro to check if a macro is defined.

How do I find the value of a macro?

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.

What is the use of conditional preprocessor directive in C?

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'.


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
like image 158
iBug Avatar answered Sep 30 '22 02:09

iBug


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
like image 29
tilz0R Avatar answered Sep 30 '22 01:09

tilz0R