Home > Software engineering >  define macro with conditional evaluation in C/C
define macro with conditional evaluation in C/C

Time:08-05

is there a way/trick to make a #define directive evaluate some condition? for example

#define COM_TIME_DO(COND, BODY) \
    #if (COND) BODY
    #else
    #endif

it's ok also to use template but body must be an arbitrary (correct in the context is used to) piece of code, simply just present or not in the source depending of COND.

as it is now the previous code doesn't even compile.

the goal of this question is primarly a better knowledge of the language and what i'm trying to do is define a debug macro system that i can activate selectively on certain parts of code for example:

A.hpp

#define A_TEST_1 1
#define A_TEST_2 0

Class A {
    ...
    COM_TIME_DO(A_TEST_1,
    void test_method_1();
    )

    COM_TIME_DO(A_TEST_2,
    void test_method_2();
    )

};

A.cpp

COM_TIME_DO(A_TEST_1,
void A::test_method_1() {
    ...
})

COM_TIME_DO(A_TEST_2,
void A::test_method_2() {
    ...
})

CodePudding user response:

i was just asking if it was POSSIBLE because i like it more than the #if ... #endif.

If the expression of the condition will always expand to 1 or 0 (or some other known set of values) it is possible to implement such a macro.

#define VALUE_0(...)
#define VALUE_1(...)  __VA_ARGS__
#define COM_TIME_DO_IN(A, ...)  VALUE_##A(__VA_ARGS__)
#define COM_TIME_DO(A, ...)  COM_TIME_DO_IN(A, __VA_ARGS__)

However, do not use such code in real life. Use #if and write clear, readable and maintainable code that is easy to understand for anyone.

CodePudding user response:

is there a way/trick to make a #define directive evaluate some condition?

This depends on what the condition actually is. Since you mentioned #if I'm assuming you'd like to evaluate an integer constant expressions.

Doing this in a macro single macro isn't possible, without implementation defined _Pragmas, but you can do it with an include a macro definition:

#define COM_TIME_DO ((1 > 2), true, false)
#include "com-time-do.h"
// ^-- generates: false
#define COM_TIME_DO ((1 == 1), true_func();, false_func();)
#include "com-time-do.h"
// ^-- generates: true_func();

where com-time-do.h is defined as follows:

// com-time-do.h
#define SCAN(...) __VA_ARGS__
#define SLOT_AT_COND(a,b,c) a
#define SLOT_AT_THEN(a,b,c) b
#define SLOT_AT_ELSE(a,b,c) c

#if SCAN(SLOT_AT_COND COM_TIME_DO)
SCAN(SLOT_AT_THEN COM_TIME_DO)
#else
SCAN(SLOT_AT_ELSE COM_TIME_DO)
#endif
#undef COM_TIME_DO

Although, as KamilCuk said, please write reasonable code and don't use this.

  • Related