single-line #ifdef in C/C++

Viewed 1638

Consider the following simple C/C++ example:

#define FOO
...
#ifdef FOO
  bar++;
#endif

OK, now I would like to fit that (and any other similar) conditional into one line for the code readability sake (the code has tens of single-line statements that all need to be conditional each depending on different define). Something that, when used, would look like:

#define FOO
...
MY_IFDEF(FOO,bar++;) //Single-line conditional

The goal is to have a reusable macro that can take an arbitrary identifier and, compile the statement if such identifier has been #define-d previously, and do it all in a single line.

Any ideas?

UPDATE0: the code must compile for both C and C++

2 Answers

You can't use #ifdef while expanding macros, but you can totally precheck it and declare empty statement if condition is not met.

#ifdef FOO
  #define MY_IFDEF(x,y) some-processing-you-need
#else
  #define MY_IFDEF(x,y) ;
#endif

Also check out new feature of C++: constexpr this can also be usable.

UPDATE4: As pointed out by @Alex Bakanov you can't use #ifdef while expanding macros, so there is no single line solution for your question which works in all cases. Nevertheless, I hope the idea I wrote here may be useful.

if you use #define FOO 1 or #define FOO 0, combination of #define and if constexpr can be used. Note that it gives an error if FOO is not defined. This program gives 1 as result:

#include<iostream>

#define FOO 1
#define MY_IFDEF(x,y) if constexpr (x) y;

int main()
{
    int bar =0;
    MY_IFDEF(FOO,bar++)

    std::cout << bar << "\n";  
}

UPDATE: Based on @eerorika's comment to avoid the error if FOO is not defined, the following declaration has to be added:

constexpr bool FOO = false;

UPDATE2: This version works in any circumstances, the only question is that is it worth the effort?

#ifdef FOO
    constexpr bool USED_FOO = true;
#else
    constexpr bool USED_FOO = false;
#endif

#define MY_IFDEF(x,y) if constexpr (USED_##x) y ;

UPDATE3: C compatible version. Note that in this case in theory it is evaluated runtime not compile time, but the compiler will realize that it is always true/false and generates the code accordingly:

#ifdef FOO
    const static bool USED_FOO = true;
#else
    const static bool USED_FOO = false;
#endif

#define MY_IFDEF(x,y) if (USED_##x) y;
Related