2

I have a situation like the following, where I have entries in a table with a macro:

#define FOR_MY_TYPES(apply) \
  apply(a, b, c) \
  apply(d, e, f) \
  ....

I also have some preprocessor conditionals:

#define CONDITION1 1
#define CONDITION2 0

I want that some entries in the table are added depending on these conditions, something like this:

#define FOR_MY_TYPES(apply) \
    apply(a, b, c) \
    #if CONDITION1 || CONDITION2
    apply(x, y, z)
    #endif

What is the best way to achieve this keeping only one macro definition, and, if possible, avoid duplicating entries depending on conditions. I want to avoid this:

#if CONDITION1
#define FOR_MY_TYPES(apply) \
   ....Full table here...
#endif
#if CONDITION2
#define FOR_MY_TYPES(apply) \
//Full table again + CONDITION2 types
#endif
#if CONDITION1 || CONDITION2
#define FOR_MY_TYPES(apply) \
//Full table again + CONDITION1 || CONDITION2 types
#endif

My problem is that there are quite a few combinations, so I should avoid replicating as much as possible. It is also more error-prone.

Germán Diago
  • 7,473
  • 1
  • 36
  • 59
  • The answer's No. There was another question asking about this scenario within the last week or so; that means there are probably other older questions that are duplicates too. – Jonathan Leffler Sep 23 '16 at 02:55
  • instead of `apply(x,y,z)` have `APPLY_12(x,y,z)` where that macro is defined in an `#if CONDITION1 || CONDITION2` – M.M Sep 23 '16 at 02:55
  • Hmm...the question I was thinking of was [Is it wrong to add preprocessor directives in a function-like macro](http://stackoverflow.com/questions/39534609), but the scenario is subtly different — it is about a macro invocation with `#ifdef` in the argument list, not in the macro definition itself as here. I stand by my comment that the direct answer is "No". (All else apart, there are problems with the backslashes continuing, or not, the lines of the macro definition. Where does the macro definition end?) – Jonathan Leffler Sep 23 '16 at 03:01

1 Answers1

4

One possible approach:

#if CONDITION1 || CONDITION2
#define really_apply(x) x
#else
#define really_apply(x)
#endif

#define FOR_MY_TYPES(apply) \
    apply(a, b, c) \
    really_apply(apply(x, y, z))
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • Works well. I still have to make macros for combinations of conditions, but at least I can keep a single table. I think there is no better way. – Germán Diago Sep 23 '16 at 03:39